Your code is a bit obsolete since WooCommerce version 3. Now on cart page, PHP redirect is useless, because Emptying cart is an Ajax customer live event. So in this case Javascript (jQuery) is required.
Use the following instead, that handle all cases:
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;
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works in all WooCommerce versions since version 3.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…