skip to Main Content

How to redirect page to shop page when last item removed from cart in woocommerce using ajax?

I am tried below code:

function cartitem_after_remove_product($cart_item_key) {
    global $woocommerce;
     $total_count = $woocommerce->cart->cart_contents_count;
     if($total_count == 0)
     {
         wp_safe_redirect( get_permalink( woocommerce_get_page_id( 'shop' ) ) );
     }
}
add_action( 'woocommerce_cart_item_removed', 'cartitem_after_remove_product' );

2

Answers


  1. You can do this via Javascript. WooCommerce has several custom events built in. Your own script can listen to these events and run your own code when they are triggered. One idea would be to check for the class "cart-empty" on updated_cart_totals.

    $( document.body ).on( 'updated_cart_totals', function(){
      // Check for empty class
      if ( $('div.woocommerce-info').hasClass( "cart-empty" ) ) {
        window.location.href = "http://www.example.com/shop/";
      }
    });
    
    Login or Signup to reply.
  2. You have to add this code into you function.php file (your theme):

    function cart_empty_redirect_to_shop() {
      global $woocommerce, $woocommerce_errors;
    
    if ( is_cart() && sizeof($woocommerce->cart->cart_contents) === 0) { 
            wp_safe_redirect( get_permalink( wc_get_page_id( 'shop' ) ) ); 
         exit;
        }
    }
    add_action( 'template_redirect', 'cart_empty_redirect_to_shop' );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search