I wanted to redirect the customer on cart page to the shop page – when emptying the cart there.
I tried this code:
add_action( 'template_redirect', 'empty_cart_redirection' );
function empty_cart_redirection(){
if( is_cart() ) :
// Here set the Url redirection
$url_redirection = get_permalink( wc_get_page_id( 'shop' ) );
// When trying to access cart page if cart is already empty
if( WC()->cart->is_empty() ){
wp_safe_redirect( $url_redirection );
exit();
}
// When emptying cart on cart page
wc_enqueue_js(
"
jQuery(function($){
$(document.body).on( 'wc_cart_emptied', function(){
if ( $( '.woocommerce-cart-form' ).length === 0 ) {
$(window.location).attr('href', '" . $url_redirection . "');
return;
}
});
});
"
);
endif;
}
This only works when reloading the page or when someone tries to go to the cart (when its empty). Does anyone know how to make it work when emptying the cart in the cart page?
Thank you so much.
2
Answers
first of all: thank you for your answer. I'm using a Astra Child Theme. I tried to create a new file footer.php and put the code you gave me there and it's working fine (this action). The problem is that then a lot of things get strange on the website. Secondly, I copied the Astra Footer file and past the code in this file; uploaded it into the child theme and then everything is okey but the redirection is not working anymore.
I don't know a lot about code, so i don't know if i'm doing something wrong.
Anyways, Thank You!!!!!
You have to add code to the footer. You can use the
wp_footer
action hook to add javascript code on the footer. You can use theupdated_wc_div
trigger as well and you can check the.cart_item
length. try the below code.Using
wc_cart_emptied
Using
updated_wc_div
Both triggers is tested and working fine.