Enric Serra Duran
Enric Serra Duran

Reputation: 71

Redirect to home if the cart is empty in Woocommerce

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

Answers (2)

LoicTheAztec
LoicTheAztec

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

Passing Through
Passing Through

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

Related Questions