How to link to images in my plugin regardless of the plugin folder’s name

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.

Related posts

Leave a Reply

4 comments

  1. 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

  2. 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]/”