我想使用 ACF 存储一个变量,然后在 wc_enqueue_js 标记中使用该变量。如果该变量可通过 php 作为 $couponCheck 使用,我需要将其作为“updated_checkout”函数内的数组提供。因此,当提交优惠券时,它会通过数组进行检查。
这有道理吗?
<?php $couponCheck = get_field('coupons');>
wc_enqueue_js( "jQuery(function($) {
// On coupon change
$(document.body).on('updated_checkout', function(){
var couponArray = XXX;
var couponCheck = $('.woocommerce-remove-coupon').attr('data-coupon');
if(jQuery.inArray('couponCheck', coupnArray)) {
$('.gift-with-coupon').show();
}
});
});");
?>
谢谢。
最佳答案
您可以使用 PHP json_encode
函数将 PHP 数组转换为 jQuery 对象。
然后您可以使用jQuery.inArray
来检查couponCheck是否存在于Javascript对象中。
$couponCheck = get_field('coupons');
wc_enqueue_js(
"jQuery(function($) {
// On coupon change
$(document.body).on('updated_checkout', function(){
var couponArray = " . json_encode( $couponCheck ) . ";
var couponCheck = $('.woocommerce-remove-coupon').attr('data-coupon');
if(jQuery.inArray('couponCheck', couponArray)) {
$('.gift-with-coupon').show();
alert('Funziona.');
}
});
});"
);
代码已经过测试并且可以工作。
关于php - 将 php 变量传递到 WordPress 查询函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67589886/