WP – Auto empty cart on homepage not working

I’m building a site with a checkout, the site has 2 products, that need to be sold individually. So to prevent people from adding the first item, leaving the cart, then adding the second item, I wanted to set up the cart to auto-empty. So I decided to test it for the homepage. The initial function I had was this:

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

That works perfectly. But the cart is always empty because of this. So I decided to add in an “if” statement:

Read More
function my_empty_cart() {
  global $woocommerce;

    if ( is_front_page() && isset( $_GET['empty-cart'] ) ) { 
        $woocommerce->cart->empty_cart(); 
    }
}
add_action( 'init', 'my_empty_cart' );

And that doesn’t work…at all. I’ve tried it with “is_home” and “is_page” (with various page titles and ids). I even tried removing the “&& isset” part, just to test. At this point i’m lost, I’ve never had this much difficulty with a simple php code and i’m pulling out my hair at this point. Is there something simple i’m just not seeing?

Related posts

Leave a Reply

2 comments

  1. this worked for me (dont relies on WordPress conditional):

    /*empty cart if user come to homepage*/
    add_action( 'init', 'woocommerce_clear_cart_url' );
    function woocommerce_clear_cart_url() {
    global $woocommerce;
    
    if ($_SERVER['REQUEST_URI'] === '/') { 
        $woocommerce->cart->empty_cart(); 
    }
    

    }

  2. Conditional tags (is_home(), is_front_page(), etc) don’t work at the time the ‘init’ hook fires. You can use ‘wp’ hook instead. It runs immediately after wp class object is set up (http://codex.wordpress.org/Plugin_API/Action_Reference/wp).

    function my_empty_cart() {
      global $woocommerce;
    
        if ( is_front_page() && isset( $_GET['empty-cart'] ) ) { 
         $woocommerce->cart->empty_cart(); 
        }
    }
    add_action( 'wp', 'my_empty_cart' );