Wordpress 在Woocommerce中-通过ajax删除购物车页面中的最后一个项目后,重定向到shop页面

Wordpress 在Woocommerce中-通过ajax删除购物车页面中的最后一个项目后,重定向到shop页面,wordpress,woocommerce,Wordpress,Woocommerce,在woocommerce中使用ajax从购物车中删除最后一项时,如何将页面重定向到商店页面 我尝试以下代码: function cartitem_after_remove_product($cart_item_key) { global $woocommerce; $total_count = $woocommerce->cart->cart_contents_count; if($total_count == 0) { wp_

在woocommerce中使用ajax从购物车中删除最后一项时,如何将页面重定向到商店页面

我尝试以下代码:

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' );

您可以通过Javascript实现这一点。WooCommerce内置了多个自定义事件。您自己的脚本可以侦听这些事件,并在触发它们时运行您自己的代码。一个想法是在更新的购物车总数上检查“购物车空”类

$( 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/";
  }
});
您必须在function.php文件>主题中添加此代码


请向我们展示您尝试过的内容,现在您可以展示上面的内容code@BInjalPatel请查看我最新发布的Ans。。。
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' );