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.

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

Leave a Reply

avatar

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

  Subscribe  
Notify of