1

I have added code to only allow 1 item in the cart at one time. However, when a user adds any item to their cart, it does NOT direct them to the Cart page.

Here is the code that I am using:

add_filter( 'woocommerce_add_cart_item_data', 'woo_custom_add_to_cart' );

function woo_custom_add_to_cart( $cart_item_data ) {
global $woocommerce;
$woocommerce->cart->empty_cart();
wc_add_notice( 'WARNING MESSAGE - You can only have 1 Item in your Cart. Previous Items have been removed.', 'error' );

return $cart_item_data;
}

So my goal is to keep this function and error message but take the user to the cart. I am sure there is something in this code that is preventing the user from going to the cart and staying on the product page.

Thanks in advance for your help!

Erik
  • 13
  • 2
  • You can redirect to the cart from the WC options. See [this answer](http://stackoverflow.com/a/15593792/383847). – helgatheviking Dec 06 '16 at 19:22
  • Thanks for the answer, but that box is already checked. I am thinking the code I mentioned above is overriding the WooCommerce options in the WordPress admin. – Erik Dec 06 '16 at 19:34
  • If you add an error then WooCommerce won't redirect. See [source](https://github.com/woocommerce/woocommerce/blob/master/includes/class-wc-form-handler.php#L718-L727). You can trying setting the notice type to "notice". – helgatheviking Dec 06 '16 at 19:52
  • If you want to use a plugin. Try "WooCommerce Poor Guys Swiss Knife" – Rohitink Dec 06 '16 at 20:01

1 Answers1

2

If you add an error then WooCommerce won't redirect. See source. You can trying setting the notice type to "notice".

Clear cart when item is added:

add_filter( 'woocommerce_add_to_cart_validation', 'so_41002991_empty_cart' );
function so_41002991_empty_cart( $valid ){
    WC()->cart->empty_cart();
    wc_add_notice( __( 'WARNING MESSAGE - You can only have 1 Item in your Cart. Previous Items have been removed.', 'your-plugin' ), 'notice' );
    return $valid;
}

There's a WooCommerce setting that will enable redirect to cart. But there's also a filter that you can optionally use:

add_filter( 'woocommerce_add_to_cart_redirect', 'so_41002991_redirect_to_cart' );
function so_41002991_redirect_to_cart( $url ){
    return wc_get_cart_url();
}
helgatheviking
  • 25,596
  • 11
  • 95
  • 152
  • The top option you mentioned worked PERFECTLY!!! Changing to a notice instead of an error did the trick! – Erik Dec 06 '16 at 20:03