Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have this Wordpress plugin file structure with "myfolder" as the main folder. There is another subfolder inside this main folder named as "resources". Inside this resources folder contains two subfolders: a) JS b.) images

Inside images folder I have one image "myimage.png". Inside JS file, I have a script named "myscript.js".

I would like to access the image "myimage.png" in images folder inside my javascript file "myscript.js".

I have tried the following but it does not work(does not resolve):

<img src="../images/myimage.png">
<img src="images/myimage.png">
<img src="resources/images/myimage.png">
<img src="../resources/images/myimage.png">
<img src="myfolder/resources/images/myimage.png">
<img src="../myfolder/resources/images/myimage.png">

Of course the absolute URL path works but I want this application to work with other sites so coding the absolute URL path is not a feasible solution.

I know that Wordpress also has this magic function:

$myicons= plugins_url('resources/images/myimage.png', __FILE__ );

But that will work only inside the PHP plugin file and I'm accessing the image inside a JS file. Any ideas how to make this work without rearranging the current file structure? Is there a JS function equivalent of "plugins_url" in Wordpress? Thanks for any tips.

share|improve this question
add comment

1 Answer 1

up vote 3 down vote accepted

For this purpose you can use wp_localize_cript() function, like this:

function localize_my_script() {
    $image_url = plugins_url( 'resources/images/myimage.png', __FILE__ );
    $localizations = array( 'imageURL' => $image_url );

    wp_localize_script( 'my-script-handle', 'localizedVars', $localizations );
}
add_action( 'wp_enqueue_scripts', 'localize_my_script' );

That is assuming that you have properly enqueued your script with my-script-handle handle as an example.

share|improve this answer
    
wow, I never thought of this solution..Thanks. –  Codex Meridian Jan 7 '13 at 5:41
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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