Search code examples
phpwordpresscustom-wordpress-pages

wordpress-passing variable from front-page.php to javascript


I am trying to access variable in javascript, that is passed from front-page.php file. I have this in front-page.php

 ...
 function pass_var_to_js() {
 $my_variable="test php var";
wp_enqueue_script('sample', get_template_directory_uri().'/assets/js/sample.js', array(), '1.0', false);
wp_localize_script('sample','jsObject', [
    'myVar' => $my_variable ]);
}
add_action('wp_enqueue_scripts', 'pass_var_to_js');
add_action('wp_body_open', 'pass_var_to_js');
...
...
<?php
    wp_body_open();
?>

and in javascript file I have

console.log(jsObject.myVar);

But it does not print variable on console

When I put the same code in functions.php , it works and prints test php var on console

How can I can pass some variables from front-page.php to javascript


Solution

  • Got it working. The issue was that , I needed to add

    add_action('wp_enqueue_scripts', 'pass_var_to_js');
      wp_head();
    

    in the <head> section of front-page.php

    this function pass_var_to_js() can remain in the body part

    After above changes , I did not needed this add_action('wp_body_open', 'pass_var_to_js');