Home » How to use PHP Data in your Javascript files for WordPress

How to use PHP Data in your Javascript files for WordPress

WordPress makes it spectacularly easy to transfer data to you javascript files if you’re unfamiliar with enqueuing scripts then please refer to my previous post. Here it goes then. Say you want to do something “fancy” like ajax calls from you js files.

I’m starting to get a little off point here right now i’d like to fully explore only localization. So ajax calls will be covered in a later post (hopefully soon)

You’ll need to use wp_localize_script to make data availabe to javascript.
Syntax: wp_localize_script( $handle, $name, $data );

function digthis_loadscript()
	wp_register_script( 'main', get_template_directory_uri(). '/js/main.js', '', '', true);
	wp_localize_script( 'main', 'Ajax',array( 'siteurl' => site_url(), ));

Let’s address the above code now :

I’m registering the script main.js in my theme. Right after that and this is important Localization must be done after scripts have been either enqueued or registered not before.

So i’m sending an object ($name) here ‘Ajax’ and data site_url() as ‘siteurl’ , Unclear? well let me make it clear with a corresponding js example

/* so this is the main.js file */

In context with this site the result will be an alert box giving digamberpradhan.com.np as a result


IMPORTANT! wp_localize_script() MUST be called after the script it’s being attached to has been registered using wp_register_script() or wp_enqueue_script().Furthermore, the actual output of the JavaScript 'script' tag containing your localization variable occurs at the time that the enqueued script is printed (output/included on the page). This has some significant repercussions if you enqueue your script as you should using the appropriate actions (wp_enqueue_scripts and admin_enqueue_scripts), but wish to localize later using data that is not available at enqueue time.

In this case, consider enqueueing your script with the in_footer argument set to true, to delay the printing of your script include until much later in the page build (ie: wp_enqueue_script( $slug, $URL, $deps, $ver, true ); ).

Happy Coding 😀

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.