Use of global variables within plugin – WordPress Development Stack Exchange

In the words of Gru, “Light~bulb!”

How to move Data from PHP to JS

Simple as it is: wp_localize_script()

Example: (can be used with login_enqueue_scripts and admin_enqueue_scripts hooks as well)

add_action( 'wp_enqueue_scripts', 'wpse115840_scripts' );
function wpse115840_scripts()
{
wp_enqueue_script( 'wpse_handle', etc... );
// Here goes the magic:
wp_localize_script( 'wpse_handle', 'wspeObject', array(
'foo' => 'bar',
'bar' => get_option( 'baz' )
) );
}

Now you can access all the data from the wp_localize_script() array (the 3rd arg) in your javascript file that you just registered/enqueued simply by calling wpseObject. The following example would now give you the value bar:

console.log( wpseObject.foo );

and your wpseObject.bar would hold your baz setting value.

via Use of global variables within plugin – WordPress Development Stack Exchange.

This is absolutely inspired… Posting it just as a reminder to use it in the future.

Updated (28 May 2014)

I finally incorporated this into a plugin I’m working on (PJ jQuery UI Helper to be exact). And it was surprisingly more difficult than I thought it would be.

The difficulty really lay in my being rather rusty in JavaScript, my final bump in the road was in using a greater than sign instead of a less than sign in my for loop… feel sheepish for that mistake, but it’s all learning even if it is stuff that I knew before (Practice makes perfect).

I plan to make a full post on the changes made to PJ jQuery UI Helper this weekend to further improve on the perfection from the practice and hopefully help somebody else who may fall into the same traps that I did.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>