JavaScript WordPress

Inject JavaScript with WordPress data it can reference using wp_localize_script()

Say you have JavaScript files that rely on images that live in your current theme directory — or elsewhere outside of the domain root — and they’re not loading without hard-coding the URL into your code.

Or, you may be developing locally and when pushing to a sandbox or production server, tired of changing the file path depending on the server.

You must register the script before calling wp_localize_script() then queueing it. This allows you to use the built-in WordPress theme directory URI or path in your scripts.

Side note: This method also allows you to access any data you’d normally only get from the server side of WordPress. Just have to plug it into your code.

Put this in your functions.php file:

wp_localize_script('custom_script', 'WPURLS', array( 'siteurl' => get_option('siteurl') )); 



And then in your .js file or <script></script> put:

var url = WPURLS.siteurl;

Test it out with something like


For more in-depth info on this, check out the official entry in the WordPress Codex.

I hope this helps!

Cheers and peace.

(Visited 3 times, 1 visits today)
0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments