WordPress path url in js script file
Asked Answered
N

6

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.

Nighttime answered 7/3, 2011 at 15:40 Comment(0)
B
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') ";
Bricky answered 7/3, 2011 at 16:7 Comment(4)
This solution works fine, but Chris answer is preferable in most situations - I didn't know about the existence of wp_localize_script().Bricky
I found this article useful. Helped me implement wp_localize_script()Dizen
Is there any reason why this would not work in 2014? besides the <?php and the weird quote style?Childbearing
<?php bloginfo("template_directory"); ?> and 'url(' + templateUrl + '/images/path-to-image.png)' would tune this baby up.Childbearing
C
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>
Carburetor answered 8/3, 2011 at 7:14 Comment(3)
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.Ogee
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().Heartland
> 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.Sammons
B
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') ";
Bricky answered 7/3, 2011 at 16:7 Comment(4)
This solution works fine, but Chris answer is preferable in most situations - I didn't know about the existence of wp_localize_script().Bricky
I found this article useful. Helped me implement wp_localize_script()Dizen
Is there any reason why this would not work in 2014? besides the <?php and the weird quote style?Childbearing
<?php bloginfo("template_directory"); ?> and 'url(' + templateUrl + '/images/path-to-image.png)' would tune this baby up.Childbearing
I
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);
Inelegance answered 12/11, 2012 at 17:32 Comment(2)
this is definitely the best and easiest way! Thank you!Trixi
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')'.Kellen
C
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;
}
Cymose answered 14/6, 2016 at 5:57 Comment(1)
Can I able to get localized variable in the theme's functions.php that set from the plugin file?Loquacity
D
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') ";
Daughter answered 9/5, 2018 at 12:33 Comment(0)
B
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.

Brachyuran answered 28/2 at 9:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.