Plugin base URL

In a question that is related to, but not the same as, How to link to images in my plugin regardless of the plugin folder’s name

  • plugin-folder/plugin-main-file.php
  • plugin-folder/images/ containing all images
  • plugin-folder/classes/ containing class definitions
  • plugin-folder/classes/class1-files containing additional files for class 1
  • plugin-folder/classes/class2-files containing additional files for class 2
  • etc

To access images, I can use relative addressing, such as plugins_url( '../images/image.png', dirname( __FILE__ ) ) but this requires a knowledge of the file structure, and a level of hard-coding that leads to potential maintenance issues.

Alternatively, I can define a global constant (eg) define('PLUGIN_ROOT', basename(dirname(__FILE__)) . "https://wordpress.stackexchange.com/" . basename(__FILE__)); in my main-file.

Ideally, there is a WordPress function that would give me the plugin base name, from anywhere in my plugin (ie always return /plugin-folder/)… but I haven’t found one. Is there such a beastie?

— EDIT TO ADD —

I am also aware of plugins_url() with no parameters… but this returns http://mydomain.ext/wp-content/plugins – ie without my plugin name!

4 Answers
4

I think you are looking for plugin_dir_url:

$url = plugin_dir_url(__FILE__);

$imageurl = $url.'images/someimage.png';

EDIT: Sorry I misread the question… that is only an answer to the linked question. You could check the parent directory recursively until you find the right one:

function base_plugin_dir($dirpath) {
    if (substr(dirname($dir),-7) == 'plugins') {return $dirpath;}
    else {$dirpath = base_plugin_dir($dirpath);}
    return $dirpath;
}

function base_plugin_dir_url($filepath) {
    $baseplugindir = base_plugin_dir(dirname($filepath));
    $url = plugin_dir_url(trailingslashit($baseplugindir));
    return $url;
}

Then you can get the URL using that function from whatever file:

$basepluginurl = base_plugin_dir_url(__FILE__);
$imageurl = $basepluginurl.'/images/wordpress.png';

OR

Better yet just set a constant from your main plugin file to use it later:

$url = plugin_dir_url(__FILE__);
define('MY_UNIQUE_PLUGIN_URL',$url);

So as to use in say /plugin/my-plugin/class/class1.php

$imageurl = MY_UNIQUE_PLUGIN_URL.'/images/wordpress.png';

Leave a Comment