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.
I am not sure about this specific example but in general
plugins_url()
is fitting function for this.Example from Codex:
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
directoryWP_PLUGIN_DIR
Absolute filepath to
wp-content/plugins
directorywp_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 thedirectory that
$file
currentlyresides in, and appends
$path
plugin_basename($file)
Get the relative path from the plugins folder to
$file
This should work for you.
http://codex.wordpress.org/Function_Reference/plugin_basename
From the example:
I think using plugin_dir_url solves this efficiently: