On the checkout page I've a button to selected the shipping method. When my cart contains a product which in in a category, I want remove all products from the cart which are in the same category.
<button onclick="clear_product_cart()">Check possibility</button>
My script :
function clear_product_cart(){
jQuery.post(
ajaxurl,
{
'action': 'clear_cart'
},
function(response){
alert( ' product removed!');
});
}
In my function.php
add_action( 'wp_ajax_clear_cart', 'clear_cart' );
add_action( 'wp_ajax_nopriv_clear_cart', 'clear_cart' );
function clear_cart(){
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( !has_term( 'my_cat', 'product_cat', $cart_item['product_id'] ) ) {
WC()->cart->remove_cart_item( $cart_item_key );
}
}
die();
}
I don't no why, but i have an error 500 after the first product was removed. Have you a suggestion? thank's