gpt4 book ai didi

javascript - 在 Ajax Woocommerce 添加到购物车验证上显示甜蜜警报

转载 作者:行者123 更新时间:2023-12-03 01:49:46 25 4
gpt4 key购买 nike

当触发 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 不会触发该功能吗?谢谢!

最佳答案

经过进一步检查,正在“验证”的项目仍会使用 ajax added_to_cart 进行调用。因此,可以使用相同的逻辑,jQuery 代码将在“added_to_cart”委托(delegate)事件上发送 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
}

关于javascript - 在 Ajax Woocommerce 添加到购物车验证上显示甜蜜警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50473397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com