Dynamic data in `wp_register_script` needed

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

function add_wp_scripts() {

    wp_register_script(
        'myscript',
        get_template_directory_uri() . '/jsfile.js',
        array(),
        null,
        true
    );

    wp_enqueue_script('myscript');    

}
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?

1 Answer
1

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.

Leave a Comment