I'm am working on a WooCommerce website, and have all my jQuery in the footer inside script tags. I use PHP to filter out the needed scripts for any particular page.
However, I would like to use the suggested method of using wp_enqueue_script to load my jquery. The trouble is that scripts containing PHP wont work unless I pass any PHP variables to he script using wp_localize_script
, which works.... mostly.
I call the enqueue in my functions.php using the wp_enqueue_scripts hook, but some of the PHP variables are not available when I register the script. Some global variables are, but some of my custom variables that are defined further down the line are empty when I try to access them via localize_script
.
I'm hoping this makes some sense? If so, how would I go about doing this properly?
For example, let's say some PHP variables are defined in a particular page template. These variables won't be accessible if I enqueue a script using the hook mentioned above. How can I enqueue a script that has access to all the PHP variables defined on the page?
The actual code is a bit complex so ill try to simplify:-
In my functions.php I have the following:-
function wp_enqueue_woocommerce_style(){
$array = array(
"var1" => <?php echo $var1 ?>,
"var2" => <?php echo $var2 ?>
);
wp_register_script('chroma_js', get_template_directory_uri() . '/js/chroma.js', '', '1.1', TRUE);
wp_enqueue_script('chroma_js');
wp_localize_script( "chroma_js", "php_vars", $array);
}
add_action( 'wp_enqueue_scripts', 'wp_enqueue_woocommerce_style',99 );
Which enqueues my script to the footer. However, the 2 PHP variables are defined in the function I hook into 'woocommerce_before_single_product'. When I try to access var1 & var2 in my script they are not defined. Any PHP variables already defined when I call the enqueue work fine. So, im not sure how to go about passing these variables to an enqueued script.
wp_localize_script()
to JS scripts