I am working on WooCommerce based Website. I have many products in it and all products are assigned to different product categories.
Now I have the requirement to completely remove products of one the category say for eg "woo-cat".
There are many custom plugins and theme in which this category's id/slug is used conditionally , So I decided not to remove category , products of that category or related code of that category.
But I redirect every possible occurrence of URL to the shop page , in which that category is include
Like I redirect - Single page of products , Category Listing Page , also hide from live search and so on ...
My problem is if any user have added products from that category in the cart , and just close browser without purchase , then it will remain in cart session , how do I remove those products of that particular category that are already in cart session.
Check screen-shot below , This is appear in top of my site :
PS : I can not do like , when user login then empty cart using _woocommerce_persistent_cart_
, because the guest user can also purchase products without login and by registering at a time of checkout page.
To remove items from session from a specific product category, you will use the following:
add_filter( 'woocommerce_pre_remove_cart_item_from_session', 'pre_remove_items_from_a_specific_category', 10, 3 );
function pre_remove_items_from_a_specific_category( $remove, $key, $values ){
// Here define your product category(ies) - can be a term id, slug orname
$categories = array('t-shirts');
if ( has_term( $categories, 'product_cat', $values['product_id'] ) ) {
$remove = true;
}
return $remove;
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.