on twitter

Follow...

Sending dynamic data to javascript in WordPress

No comments

The enqueue system for javascript/css files within Wordpress is terrific, and can be even more powerful with the knowledge that you can pass dynamic data over to your external javascript files with ease.

This is useful for a whole host of reasons. Many jQuery plugins (like the awesome¬†jplayer) require absolute paths to certain directories, and passing the path through here is tidy and clean. You could also run a wp_query, grab out a group of custom field data, let’s say, a playlist of mp3s, and send them over to the javascript file to be loaded up.

For this example, I’m running a function in my theme’s functions.php file, to load up a specific js file if we’re on the homepage:

1
2
3
4
5
6
7
8
9
10
11
12
function my_custom_enqueue_scripts() {

if(is_front_page())
{

wp_enqueue_script( 'home-js', get_bloginfo('template_url') . '/js/home.js', array( 'jquery' ));

}

}

add_action( 'wp_enqueue_scripts', 'my_custom_enqueue_scripts' );

It’s good to conditionally queue javascript files if you have a particularly js heavy site, or just want to streamline page loads as best you can. The same applies to page specific css files.

Here, we’ve set up an enqueue script with the tag “home-js”, told WordPress where it’s located and explained that it depends on jQuery.

We can now use wp_localize_script to send over data to this home.js file, like so:

1
2
3
4
5
6
7
8
9
10
11
12
function my_custom_enqueue_scripts() {

if(is_front_page())
{

wp_enqueue_script( 'home-js', get_bloginfo('template_url') . '/js/home.js', array( 'jquery' ), null, true );
wp_localize_script( 'home-js', 'PassThisOver', array( 'myDinner' => 'Hummus and avacado pancake') );
}

}

add_action( 'wp_enqueue_scripts', 'my_custom_enqueue_scripts' );

The array is sent over as an object, so to reference my string I can simply use:

1
2
3
4
5
6
7
8
9
(function($){

$(document).ready(function($){

alert(PassThisOver.myDinner);

});

})(jQuery);

Hope this comes in handy for you.

Leave a Reply