Erik
Erik

Reputation: 13

WooCommerce Redirect to Cart After Item Added

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!

Upvotes: 1

Views: 902

Answers (1)

helgatheviking
helgatheviking

Reputation: 26319

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();
}

Upvotes: 2

Related Questions