2

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.

8

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__);
0
6

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

0

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]/"

0

I think using plugin_dir_url solves this efficiently:

$url = plugin_dir_url(__FILE__);

$imageurl = $url.'images/wordpress.png'l

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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