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:
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?
this worked for me (dont relies on WordPress conditional):
}
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).