Reputation: 71
I am looking for and can not find anywhere as I can redirect the empty woocommerce cart to the homepage. I only find redirects that go to the store.
This is what I find, but I do not need to redirect to the home:
add_action("template_redirect", 'redirection_function');
function redirection_function(){
global $woocommerce;
if( is_cart() && WC()->cart->cart_contents_count == 0){
wp_safe_redirect( get_permalink( woocommerce_get_page_id( 'shop' ) ) );
}
}
Context link: If cart is empty, the cart page will redirect to shop page in WooCommerce?
Upvotes: 1
Views: 4577
Reputation: 253804
To redirect to home if cart is empty you will use a similar code:
add_action( 'template_redirect', 'empty_cart_redirection' );
function empty_cart_redirection(){
if( WC()->cart->is_empty() && is_cart() ){
wp_safe_redirect( esc_url( home_url( '/' ) ) );
exit;
}
}
Code goes in function.php file of your active child theme (active theme). Tested and works.
But if cart is emptied through ajax, this code will enable a redirection to home until the page will be reloaded.
Upvotes: 3
Reputation: 9
For those finding this via search (like me) the code that Loic provided works with one small change if you're wanting the empty cart to redirect back to the homepage:
add_action( 'template_redirect', 'empty_cart_redirection' );
function empty_cart_redirection(){
if( WC()->cart->is_empty() && ( ! is_front_page() || is_cart() ) ){
wp_safe_redirect( esc_url( home_url( '/' ) ) );
exit;
}
}
Upvotes: 0