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.

What is the correct method to refer to images from within your plugin code, so that no matter what the folder is named, they resolve correctly?

I had an issue where a user downloaded my plugin twice, then used the 2nd downloaded file to install it. Since Windows automatically named duplicate files foldername(2).zip, when my plugin was uploaded to the site, it was placed in a folder named "foldername(2). So since my images were linked to wp-content/plugins/foldername/img/foo.png, none of the images were showing up.

share|improve this question

3 Answers 3

up vote 5 down vote accepted

I am not sure about this specific example but in general plugins_url() is fitting function for this.

Example from Codex:

plugins_url('/images/wordpress.png', __FILE__);
share|improve this answer
    
+1 - would be my suggestion to.. :) –  t31os Dec 10 '10 at 14:46

As has already been said, use plugins_url($path, $plugin_file).

You should always avoid hard-coding paths as much as possible, since not only can a user rename a plugin folder, they can move the entire wp-content directory!

Here's a few functions and constants I always use;

  • WP_CONTENT_DIR
    Absolute filepath to wp-content directory

  • WP_PLUGIN_DIR
    Absolute filepath to wp-content/plugins directory

  • wp_upload_dir($time)
    Get filesystem and URL paths to uploads directory, optionally for a specific time (if using year/month folders)

  • site_url($path)
    Absolute URL to WordPress install

  • home_url($path)
    Absolute URL to WordPress home (front page per se)

  • plugins_url($path, $file)
    Uses plugin_basename($file) to get the absolute URL for the directory that $file currently resides in, and appends $path

  • plugin_basename($file)
    Get the relative path from the plugins folder to $file

share|improve this answer

This should work for you.

http://codex.wordpress.org/Function_Reference/plugin_basename

From the example:

If your plugin file is located at /home/www/wp-content/plugins/myplugin/myplugin.php, and you call:

$x = plugin_basename(__FILE__); 

$x will equal "myplugin/myplugin.php".

If you would like to know the full url path to your plugin's directory, you can call:

$x = WP_PLUGIN_URL.'/'.str_replace(basename( __FILE__),"",plugin_basename(__FILE__));

$x will equal "http://[url-path-to-plugins]/[myplugin]/"

share|improve this answer

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.