Redirect if basket is empty | Woocommerce 3+

Asked

Viewed 137 times

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 intend to redirect to the main page if the cart is empty!
Redirecting is only possible if you refresh the page ( F5 ).

Thanks in advance!

  • Following your line of reasoning the path I see there would be javascript friend, try to take advantage of the jquery library.

1 answer

0

Every (or almost every) empty cart in wordpress has the p tag 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();
  • It doesn’t work, but thanks anyway!

  • It works. It depends on how you applied.

  • I applied it well, it doesn’t work. Thanks in the same Oak!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.