Pass php variable into Wordpress Query function

Viewed 197

I would like to use ACF to store a variable which I then use in a wc_enqueue_js tag. If the variable is available via php as $couponCheck, I need to make it available as an array inside the 'updated_checkout' function. So then when the coupon is submitted it gets checked with the array.

Does that makes sense?

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

Thanks.

1 Answers

You can use PHP json_encode function to convert PHP array to jQuery object.

Then you can use jQuery.inArray to check if couponCheck is present in the Javascript object.

$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.');
            }
        });
    });"
);

The code has been tested and works.

Related