Here bellow code we checking if tips category items added to WooCommerce cart, then we removed the other all items are in cart.
you can check multiple categories by adding comma separated categories $categories array
$categories = array( 'tips','somecategory' );
once items are successfully removed from your cart then we can show the WC notice
$notice = sprintf(
// // Translators: Placeholder is for cart url.
__( 'We removed your other items in cart' ),
esc_url( wc_get_cart_url() )
Here are the Full PHP code. you can place this in function.php
function remove_items_from_cart_by_category() {
// Add categories. Multiple can be added, separated by a comma
$categories = array( 'tips' );
// Initialize
$cart_item_keys = array();
$has_category = false;
// WC Cart NOT null
if ( ! is_null( WC()->cart ) ) {
// Loop through cart items
foreach ( WC()->cart->get_cart_contents() as $cart_item_key => $cart_item ) {
// Get product id
$product_id = $cart_item['product_id'];
// NOT certain category
if ( ! has_term( $categories, 'product_cat', $product_id ) ) {
// Push to array
$cart_item_keys[] = $cart_item_key;
} else {
$has_category = true;
}
}
// NOT empty & has category is true
if ( ! empty ( $cart_item_keys ) && $has_category ) {
// Loop through all cart item keys that do not contain the category
foreach ( $cart_item_keys as $cart_item_key ) {
// Remove product from cart
WC()->cart->remove_cart_item( $cart_item_key );
$notice = sprintf(
// // Translators: Placeholder is for cart url.
__( 'We removed your other items in cart' ),
esc_url( wc_get_cart_url() )
);
wc_add_notice( $notice, 'notice' );
}
}
}
}
add_action( 'woocommerce_checkout_before_customer_details', 'remove_items_from_cart_by_category', 10, 0 );
An all round web designer building websites Over 18 years. Interested in achieving a suitable placement in the field of IT in a growth oriented organization which offers diverse job responsibilities in order to utilize and improve my skills, Knowledge and experience.