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

Inject JavaScript with WordPress

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:

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

wp_enqueue_script('custom_script');

?>

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

var url = WPURLS.siteurl;

Test it out with something like

alert(url);

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

I hope this helps!

Cheers and peace.

(Visited 155 times, 1 visits today)

If you found this post useful ...

Buy Me a Coffee logo
Wondering why you keep seeing lower-cased 'i' in my posts? Read -> Why ‘i’ is not capitalized
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x