If you have ever written a plugin that uses any form of Javascript, you will probably have come across the problem of passing configuration options from PHP to Javascript. Take an image slider plugin, such as Soliloquy for example: most likely there is a settings page of some kind that lets the user set the transition type, the timing, the number of slides, etc. These are all options that need to be available in the JS for the slider. The problem at hand is this: how can JS read data from PHP? It’s quite simple actually.

In order for JS to read data from PHP, the data we want read must be translated into Javascript from PHP. To do this all we need to do is setup a function that outputs a global JS variable so that our JS file can read it. Take the example below:

1
2
3
4
5
6
7
8
function pw_global_js_vars() {
	echo '<script type="text/javascript">
	/* <![CDATA[ */
	var pw_php_vars = {"var_name":"var_value"};
	/* ]]> */
	</script>';
}
add_action( 'wp_head', 'pw_global_js_vars' );

This will insert a global JS object call “pw_php_vars” into the head section of our site. Since it is global, any JS file can read it now, like this:

1
2
3
jQuery(document).ready(function() {
	alert( pw_php_vars.var_name );
});

Now let’s go a little further and add some actual PHP into our global JS function:

1
2
3
4
5
6
7
8
9
10
11
function pw_global_js_vars() {
 
	$timing = get_option( 'pw_slide_timing' );
 
	echo '<script type="text/javascript">
	/* <![CDATA[ */
	var pw_php_vars = {"timing":"' . $timing . '"};
	/* ]]> */
	</script>';
}
add_action( 'wp_head', 'pw_global_js_vars' );

This example illustrates how you might pull an option from the database and make it available to your JS. Reading it in the JS file would then look like this:

1
2
3
4
5
jQuery(document).ready(function() {
	someJSFunction({
		delay: pw_php_vars.timing
	});
});

It may look a little complex, but it’s really quite simple once you get an understanding of what is happening. Now, let’s make it much, much easier.

WordPress has a fantastic function called wp_localize_script() that does all of this for us.

Using wp_enqueue_script() you will first load your JS file, like so:

1
2
3
4
5
6
function pw_load_js() {
 
	wp_enqueue_script( 'pw-script-handle', PW_PLUGIN_FOLDER . 'js/pw-scripts.js', array( 'jquery' ) );
 
}
add_action( 'wp_enqueue_scripts', 'pw_load_js' );

Inside of my pw-scripts.js file I then want to reference data from PHP / the database. To do this, we use wp_localize_script() to setup our global JS variables, like so:

1
2
3
4
5
6
7
8
9
10
11
12
function pw_load_js() {
 
	wp_enqueue_script( 'pw-script-handle', PW_PLUGIN_FOLDER . 'js/pw-scripts.js', array( 'jquery' ) );
 
	wp_localize_script( 'pw-script-handle', 'pw_php_vars', array(
			'timing' => get_option( 'pw_slide_timing' ),
			'effect' => get_option( 'pw_slide_effect' )
		)
	);
 
}
add_action( 'wp_enqueue_scripts', 'pw_load_js' );

This will result in the exact same output as I described above, but we let WordPress handle the generation and output of the global JS. All we need to do is pass an array of the variables we need to make available. Pretty slick right?

wp_localize_script() was first designed to make it possible to pass localized text strings to the Javascript for alerts and other messages, but it works perfectly for arbitrary variables as well.

  1. Brad

    Nice! I’ll definitely leverage the wp_localize_script() function in the future. I’ve been doing it the first way you showed, except loading it into the footer with the ‘wp_footer’ hook instead.

    • Pippin

      The wp_footer hook is probably the better one to use if you are going to do it manually, but personally I wouldn’t ever do it manually 🙂

  2. Jean

    Thanks Pippin!

  3. Agnel Waghela (@agnel_waghela)

    Thanks Pippin! One of the most needed hook in any plugin/theme development!

  4. Uriel

    I was just wondering if there is a way to dosomething like this for css files, specially for referencing folders and stuff like that…

    • Pippin

      Not that I have ever heard of.

  5. sayed taqui

    Thanks, I was looking for this. And your website has very usefull articles , I loved it. awesome job.

  6. ujwal dhakal

    Damn man ur god i read about more than 20 articles related to this watched many videos but this single function

    function pw_global_js_vars() {

    $timing = get_option( ‘pw_slide_timing’ );

    echo ‘
    /* */
    ‘;
    }
    add_action( ‘wp_head’, ‘pw_global_js_vars’ );

    made me understand the whole thing thank you bro alot

  7. Suman Samanta

    I am bookmarking your article so I can revisit and review more of your content. I agree with many of your thoughts and am impressed with your out-of-the box thinking.

  8. Cabinet Abbad

    Right here is the perfect web site for everyone who hopes to
    find out about this topic. You understand
    a whole lot its almost hard to argue with you (not that I
    really would want to…HaHa). You definitely put a brand new
    spin on a topic that has been written about for years.

    Great stuff, just great!

  9. Model Hunter

    You can definitely see your skills within the work you write.
    The world hopes for more passionate writers
    such as you who are not afraid to mention how they believe.

    All the time go after your heart.

  10. scr888 wukong

    As Tom along with the owner of the farm point out at the Judges’ Table, baby lamb meat is naturally
    tender. I LOVE ACTING, and experienced some success with
    it so far. Louis and reator off The best way to Get .

    My homepage scr888 wukong

Comments are closed.