Developer // Accessing WordPress URL Function Values Within Javascript

During my custom WordPress theme development I often find that it would be really useful if I could just use the WordPress get_template_directory_uri() or home_url() functions from within Javascript.

For example when trying to set the url of an Ajax request in jQuery, or setting the path to an icon image file on a Google Map.

Thankfully, if you’re using WordPress in the way it’s intended, there is a very simple way to make this possible.

The wp_localize_string() function does exactly what we are trying to do – allows us to take an array of PHP generated data and makes it accessible in a JavaScript object.

The only prerequisite being that you must be using the wp_register_script() and wp_enqueue_script() functions to load in you Javascript files for wp_localize_script() to work.

It takes 3 parameters, the first being the name of you registered your script under, (with the wp_register_script function), the second parameter being the name you want to give your JavaScript object. Finally the third parameter is the array of data you wish to be translated into items within the JavaScript object.

In the code above you can see i’ve added a globalObject containing the output of 2 different WordPress functions that I wish to access in my JavaScript.

The wp_localize_script() function must be called after the script has been registered, but before it is enqueued.

The object items can then be used in JavaScript as follows:


Leave a Reply

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