I'm using wp_register_script and wp_enqueue_script in functions.php is like this:

function add_wp_scripts() {

        get_template_directory_uri() . '/jsfile.js',


add_action( 'wp_enqueue_scripts', 'add_wp_scripts' );

This works fine. The jsfile.js contains just two static hard coded data that do not change often.

Now I have to evaluate if it is possible to get dynamic data from database and to put this data into jsfile.js? - Since yet,I have no experience with JavaScript and I would like to know if it possible get dynamic data in jsfile.js? If yes, how could I realize this and are there any restrictions from WordPress itself?


You are looking for the wp_localize_script() function. This function allows you to add data from server to your javascript.

However, this will not change the content of jsfile.js. Instead, it will add some global variable in your theme's footer.Changing the content of a JS file before outputting it to the browser is an advanced technique, and requires compiling/buffering. The above function should be enough for most of the users.

Everything you need about how to use the function is included in the provided link.

  • Thank you, Jack. I have to read in first. Seems to be a little complex.
    – Peter
    May 4 '18 at 19:30
  • Maybe there exists a workaround? - My idea is to write a php script that produces the jsfile.js cron-based (i.e. monthly). It's a work-around, but it could be more effective for me to realize.
    – Peter
    May 4 '18 at 19:35
  • It's actually easy to use, if you follow the examples. You have to notice, if you generate the JS file, it will be cached by the browsers. Forcing the user to download a full JS file just to update some data is not very optimistic.
    – Jack Johansson
    May 4 '18 at 19:56
  • I think, wp_localize_script() should be the needed function for my case. But the documentation on Wordpress page is far too superficially. The description is quite short and the example is not clear and not helpful.
    – Peter
    May 5 '18 at 16:16
  • You can try this alternative link, and check users examples. They are clearer.
    – Jack Johansson
    May 5 '18 at 16:22

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.