Redirect if the basket is empty | Woocommerce 3+

0
add_action( 'wp_footer', 'redirecionar' );
function redirecionar(){
    global $woocommerce;
    if ( is_page('carrinho-de-compras') and !sizeof($woocommerce->cart->cart_contents) ) {
        wp_redirect( get_home_url() );
        exit();
    }
}

OR

add_action( 'template_redirect', 'redirecionar' );
function redirecionar(){
    global $woocommerce;
    if( is_cart() && WC()->cart->cart_contents_count < 1 ){
        wp_safe_redirect( get_permalink( woocommerce_get_page_id( 'shop' ) ) );
    }
}

I want to redirect to the homepage if the cart is empty! Redirection is only possible if you refresh the page (F5).

Thanks in advance!

    
asked by anonymous 24.05.2018 / 15:09

1 answer

0

All (or almost all) empty cart in wordpress has the tag p with the class cart_empty, so with a simple Javascript you can check the length and if it is greater than 0, it is because the cart is empty, and then , redirects.

const redirectIfEmpty = () => {
    const lengthCartEmpty = document.getElementsByClassName('cart-empty').length;
    if(lengthCartEmpty > 0){
        window.location.href = 'www.seusite.com.br';
    }
}

redirectIfEmpty();
    
05.07.2018 / 18:37