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.
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:
To access this variable within in Javascript, you would simply do:
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: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):
and in custom.js
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.
For users working with the Genesis framework.
Add the following to your child theme
functions.php
And use that variable to set the relative url in your script. For example: