Properly get your Plugin’s Path and URL
In the past, countless effort was made in determining the location of a plugin, including the path and the URL. It was truly a pain to guess the correct directory that a plugin belongs to (guessing does mean that it can be wrong sometimes, you know).
Such tedious task is no longer an issue as of WordPress 2.8. In version 2.8, two useful functions were introduced, namely
plugin_dir_path(), both can be located in
To use those two functions, all you need to do is to pass a
$file parameter which is basically the path to the main PHP file of your plugin. Yet another path, eh? Fortunately getting this path is much more easier than guessing the whole thing.
In order to get the correct path to pass into the
$file parameter, use this:
- $file = dirname(__FILE__) . '/your-main-php-file.php';
- $plugin_url = plugin_dir_url($file);
- // Output something like: http://example.com/wp-content/plugins/your-plugin/
- $plugin_path = plugin_dir_path($file);
- // Output something like: /home/mysite/www/wp-content/plugins/your-plugin/
$file = dirname(__FILE__) . '/your-main-php-file.php'; $plugin_url = plugin_dir_url($file); // Output something like: http://example.com/wp-content/plugins/your-plugin/ $plugin_path = plugin_dir_path($file); // Output something like: /home/mysite/www/wp-content/plugins/your-plugin/
If you happen to use this code in a PHP file inside a sub-folder, simply use more
dirname()1 functions, like so:
- $file = dirname(dirname(__FILE__)) . '/your-main-php-file.php';
$file = dirname(dirname(__FILE__)) . '/your-main-php-file.php';
This way all the paths and URLs should be correct (even if you install your plugin as a must-use plugin!).
plugin_dir_path() will automatically add a trailing slash to the URL and path so please keep that in mind when you try to append something (to avoid the double slashes issue).