53

I added custom script:

wp_enqueue_script('functions', get_bloginfo('template_url') . '/js/functions.js', 'search', null, false);

It works great, except in the functions.js I have:

Reset.style.background = "url('../images/searchfield_clear.png') no-repeat top left";

This used to work before, until I changed to pretty permalinks and .htaccess

The folder hierarchy is like:

themename/js themename/images (the images and js folder are in themename folder)

I tried ../images - ./image - /images

Normally it should go back 1 level wherever the js file is located....

I don't want to use full path.

Is there another way that WordPress can recognize in the javascript file to have the correct path?

Currently I am just confused what I am doing wrong.

6 Answers 6

120

According to the Wordpress documentation, you should use wp_localize_script() in your functions.php file. This will create a Javascript Object in the header, which will be available to your scripts at runtime.

See Codex

Example:

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

To access this variable within in Javascript, you would simply do:

<script type="text/javascript">
    var url = WPURLS.siteurl;
</script>
3
  • 1
    It would be nice if you also showed how to fetch the variable in JavaScript. I know it shows how in the link, but it would make a more complete answer. Commented Jan 7, 2015 at 13:30
  • 19
    Maybe this note from the documentation should be mentioned as well: IMPORTANT! wp_localize_script() MUST be called after the script has been registered using wp_register_script() or wp_enqueue_script(). Commented May 26, 2015 at 7:53
  • 1
    > wp_add_inline_script() was introduced in WP v4.5, and is now the best > practice for that use case. wp_localize_script() should only be used > when you actually want to localize strings. Commented Oct 16, 2020 at 13:29
70

You could avoid hardcoding the full path by setting a JS variable in the header of your template, before wp_head() is called, holding the template URL. Like:

<script type="text/javascript">
var templateUrl = '<?= get_bloginfo("template_url"); ?>';
</script>

And use that variable to set the background (I realize you know how to do this, I only include these details in case they helps others):

Reset.style.background = " url('"+templateUrl+"/images/searchfield_clear.png') ";
4
  • 8
    This solution works fine, but Chris answer is preferable in most situations - I didn't know about the existence of wp_localize_script().
    – AJJ
    Commented Mar 9, 2011 at 16:30
  • 1
    I found this article useful. Helped me implement wp_localize_script() Commented Sep 12, 2013 at 21:54
  • 1
    Is there any reason why this would not work in 2014? besides the <?php and the weird quote style? Commented Apr 24, 2014 at 2:01
  • <?php bloginfo("template_directory"); ?> and 'url(' + templateUrl + '/images/path-to-image.png)' would tune this baby up. Commented Apr 24, 2014 at 2:20
28
    wp_register_script('custom-js',WP_PLUGIN_URL.'/PLUGIN_NAME/js/custom.js',array(),NULL,true);
    wp_enqueue_script('custom-js');

    $wnm_custom = array( 'template_url' => get_bloginfo('template_url') );
    wp_localize_script( 'custom-js', 'wnm_custom', $wnm_custom );

and in custom.js

alert(wnm_custom.template_url);
2
  • 1
    this is definitely the best and easiest way! Thank you!
    – danyo
    Commented Jul 1, 2013 at 11:33
  • 2
    I know this is an old post, but to get the child themes URL use 'get_stylesheet_directory_uri()' instead of 'get_bloginfo('template_url')'.
    – Hubvill
    Commented Nov 23, 2015 at 18:27
7

If the javascript file is loaded from the admin dashboard, this javascript function will give you the root of your WordPress installation. I use this a lot when I'm building plugins that need to make ajax requests from the admin dashboard.

function getHomeUrl() {
  var href = window.location.href;
  var index = href.indexOf('/wp-admin');
  var homeUrl = href.substring(0, index);
  return homeUrl;
}
1
  • Can I able to get localized variable in the theme's functions.php that set from the plugin file? Commented Dec 25, 2017 at 6:47
1

For users working with the Genesis framework.

Add the following to your child theme functions.php

add_action( 'genesis_before', 'script_urls' );

function script_urls() {
?>
    <script type="text/javascript">
     var stylesheetDir = '<?= get_bloginfo("stylesheet_directory"); ?>';
    </script>
<?php
}

And use that variable to set the relative url in your script. For example:

Reset.style.background = " url('"+stylesheetDir+"/images/searchfield_clear.png') ";
0

I've gotten it to work by using this method...

1: Adding the callback function into the header

function custom_header() {
// Define siteURL for JS
echo '<script>var url = "'.home_url().'";</script>';
}
add_action( 'wp_head', 'custom_header' );

2: Call the URL inside any desired JS file as follows:

$.infinitescroll.defaults = {
      loading: {
        msgText: 'Loading...',
        img: "" + url + "/path_to_folder/loader.gif",
      }

Hope it can help anyone looking to include a site URL in inner JS or CSS files.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.