在Woocommerce中-当通过Ajax删除商品中的购物车页面中的最后一个商品后重定向到商店页面

时间:2020-08-26 09:38:16

标签: wordpress woocommerce

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

我尝试使用以下代码:

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 个答案:

答案 0 :(得分:0)

您可以通过Javascript执行此操作。 WooCommerce内置了几个自定义事件。您自己的脚本可以侦听这些事件,并在触发它们时运行您自己的代码。一种想法是在updated_cart_totals上检查“ cart-empty”类。

$( 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/";
  }
});

答案 1 :(得分:0)

您必须在function.php文件中添加此代码>您的主题

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