1

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?

Zoe
  • 27,060
  • 21
  • 118
  • 148

2 Answers2

3

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.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • Hello LoicTheAztec, first of all, thanks for your interest. Unfortunately, I have added the code to the function.php of my theme and it does not react. It's as if you do nothing. I can assure you that the code previously written to my question works correctly but it redirects to the store. I do not understand why yours does not redirect to any place. Thank you again – Enric Serra Duran Nov 13 '18 at 20:38
  • @EnricSerraDuran The code works when cart is empty and redirect to home page. Now in cart page you can not use it as it will avoid empty cart and make an error, so it's not effective in cart page with the condition `! is_cart()`. – LoicTheAztec Nov 13 '18 at 20:44
  • Is there a way to check if the cart is empty when its updating with ajax? @LoicTheAztec – Webbie Oct 20 '19 at 22:50
0

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