如何使用ajax在wooccommerce中从购物车中删除最后一个商品时将页面重定向到商店页面?
我尝试了以下代码:
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' );
您必须将此代码添加到函数.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' );
您可以通过Javascript实现这一点。WooCommerce内置了几个自定义事件。您自己的脚本可以监听这些事件,并在触发它们时运行自己的代码。一个想法是检查类";推车为空";在updated_cart_tals上。
$( 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/";
}
});