Negor Ubeyd
Negor Ubeyd

Reputation: 37

Woocommerce - Clear cart on home page (doesn't work while logged in)

I'm trying to clear the cart on home page. I've added this part to home page head section:

 <script type='text/javascript'>      
    function clearCart() {
            jQuery.post(
                "https://abcdefgh.com/wp-admin/admin-ajax.php", 
                //ajaxurl, 
                {
                    "action": "clearcart"
                } 

            );
  console.log('its homepage bro!');
 }  
  jQuery(document).ready(function(){
    clearCart();
  });
  </script>

And, added this part to functions.php:

add_action('wp_ajax_nopriv_clearcart',function(){
    global $woocommerce;
    $woocommerce->cart->empty_cart(true);
  });

If the user is not logged in, the cart is cleared on the home page. But, if the user is logged in, it does not work although the javascript part is executed (I checked via console log.).

Why do you think it happens and how can I resolve it?

Upvotes: 3

Views: 1571

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253939

You don't need to use Ajax for that. I just use optionally a bit of jQuery to Refresh / update related cart data (like in mini-cart):

add_action( 'wp_footer', 'clear_the_cart_in_home_refresh' );
function clear_the_cart_in_home_refresh(){
    // Just in home page when cart is not empty
    if( WC()->cart->is_empty() ) return;
    if( ! is_front_page() ) return;

    // Empty cart
    WC()->cart->empty_cart(true);
    WC()->session->set('cart', array());

    // Reset minicart count and update page content (if needed)
    ?>
    <script type='text/javascript'>
        jQuery(document).ready(function($){
            setTimeout(function() {
                $('body').trigger('wc_fragment_refresh');
                $('body').trigger('updated_wc_div');
            }, 100);
        });
    </script>
    <?php
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works.

Upvotes: 4

Related Questions