我试图在触发woocommerce_add_to_cart_validation
时在商店存档页面上显示甜蜜警报(javascript)...
Javascript Sweet Alert不会触发:
// remove the page error redirect
add_filter( 'woocommerce_cart_redirect_after_error', '__return_false');
add_action( 'woocommerce_add_to_cart_validation', 'restrict_items_in_cart' );
function restrict_items_in_cart($cart_item_data) {
global $woocommerce;
$item_count = $woocommerce->cart->cart_contents_count;
//IF CONDITION TO VALIDATE CART
if($item_count > 1){
//JAVASCRIPT ALERT TO BE DISPLAYED. BUT DOES NOT TRIGGER
?>
<script src="https://unpkg.com/sweetalert2@7.20.1/dist/sweetalert2.all.js"></script>
<script type="text/javascript">
swal(
'TOO MANY ITEMS!',
'Want to change?',
'error')
</script>
<?php
}
return $cart_item_data;
}
通过AJAX将商品添加到商店/存档页面的购物车中......任何想法为什么javascript不会触发该功能?谢谢!
答案 0 :(得分:1)
进一步检查后,仍然使用ajax added_to_cart
调用正在“验证”的项目。因此,可以使用相同的逻辑,其中jQuery代码将在“added_to_cart”委托事件上发送ajax请求。在该请求上,php将获得将购物车项目添加到购物篮的尝试次数,并将其返回给jQuery。如果该计数符合条件,则会显示甜蜜警告消息:
感谢@LoicTheAztec帮助提供部分解决方案。
// remove the filter
add_filter( 'woocommerce_cart_redirect_after_error', '__return_false');
add_action( 'woocommerce_add_to_cart_validation', 'restrict_only_one_item_in_cart' );
function restrict_only_one_item_in_cart($cart_item_data) {
global $woocommerce;
$item_count = $woocommerce->cart->cart_contents_count;
if($item_count >= 20)
{
//WE WILL EXECUTE JAVASCRIPT BELOW INSTEAD
return false;
}
return $cart_item_data;
}
// The Jquery script
add_action( 'wp_footer', 'cart_full' );
function cart_full() {
?>
<script src="https://unpkg.com/sweetalert2@7.20.1/dist/sweetalert2.all.js"></script>
<script type="text/javascript">
jQuery( function($){
// The Ajax function
$(document.body).on('added_to_cart', function() {
console.log('event');
$.ajax({
type: 'POST',
url: wc_add_to_cart_params.ajax_url,
data: {
'action': 'checking_cart_items',
'added' : 'yes'
},
success: function (response) {
if( response >= 20 ){
swal(
'Youve added the max items!',
'Change Your box',
'error'
);
}
}
});
});
});
</script>
<?php
}