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
<?php wp_localize_script('custom_script', 'WPURLS', array( 'siteurl' => get_option('siteurl') )); wp_enqueue_script('custom_script'); ?>
And then in your
.js file or
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.