Passing data from PHP to the enqueued scripts in WordPress

tumblr_nau9zqjZay1tubinno1_1280

Enqueueing scripts, while being as one of the most common tasks for WordPress theme and plugin developers, has a very nice companion feature that can be used to pass data to it. These data will then be available in the native scope of those scripts. In this short article, I am going to show you how to to this

Remember the first parameter of wp_enqueue_script() function? It’s called ‘handle’, and works as a reference point. We need this handle to send some data to it with the help of wp_localize_script() function. Let’s have a look at the following example.

[sourcecode language=”php”]
add_action("wp_enqueue_scripts","my_scripts_loader");

function my_scripts_loader(){
$data = array("home"=>site_url());

wp_enqueue_script("myscript","path/to/my/script.js");
wp_localize_script( "myscript", "blog", $data );

}
[/sourcecode]

wp_localize_script() takes the handle of the script file, a variable name and an array. Finally, wp_localize_script converts that array into a JSON object and makes available in the local scope of that javascript file via that variable name. So, from the example above you can write the following code in your script.js and it will show you your blog URL, which was actually passed to it using wp_localize_script function

[sourcecode language=”javascript”]
alert(blog.home);
[/sourcecode]

This feature is pretty handy for developing themes and plugins, to pass data from your PHP scripts to the external javascript files. Hope you’ve enjoyed this article.