0
votes

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

1
Solved. My error are simple i have add " session_start " in my custom shipping methode. The error 500 are show because the session are previously declared. - Mike

1 Answers

0
votes

Your JavaScript function could be the problem. Please remove it and put this into your functions.php file of your child theme:

add_action( 'wp_head', 'head_data' );
function head_data() { ?>

    <script>
        function clear_product_cart() {

            let a = {action: "clear_cart"};

            jQuery.post("<?php echo admin_url( 'admin-ajax.php' ); ?>", a, function () {
            }).success(function () {
                alert('Product removed!');
            }).fail(function () {
                alert('Error!');
            });
        }
    </script>
<?php }

Try it again and tell me if it works. I can't test it at the moment.