1

I have been looking for a help on the forum, but nothing matches really my problem.

I am actually trying to use bxSlider with Wordpress. My problem is that where I create my gallery image (a template page in a child theme) I need to pass the image's urls that I got dynamically from previous page to js file to create my gallery image with the option propose by bxslider. (In particular with thumbnail)

To pass variables from php to js, I normally use wp_localize_script in function.php or a plugin but not a template page. And in this case I can't even enqueue my script.

How can I pass variables from template page to javascript file with dynamic variable (so impossible for me to pass through function.php)

Thank you for your help !

0

I finally solved it ! :)

The problem was that I add my function to localize and enqueue my script at the end of the page with the function itself, after wordpress loop. So I finally add the function before to get the header and this time, I can pass variables normally.

(I already register my script in function.php)

Code before (wrong) :

[...Code...]
function pass_var_to_js() {
    global $my_variable;
    wp_localize_script('script_name','send_var', array( $my_variable ) );
    wp_enqueue_script('script_name');
}
add_action('wp_enqueue_scripts', 'pass_var_to_js');

Code after (right) :

[...Code...]
add_action('wp_enqueue_scripts', 'pass_var_to_js');
get_header();
[...Code...]
function pass_var_to_js() {
    global $my_variable;
    wp_localize_script('script_name','send_var', array( $my_variable ) );
    wp_enqueue_script('script_name');
}

I hope that it could help someone !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.