Determine Plugin Directory and URL in WordPress using WP API

While developing my own WordPress Plugins, I had many occasions where I had to know the URL of the plugin. Especially while including some JavaScript or Stylesheets. Using a relative path is not a good solution for this. As many users have their own content folder. As of WordPress 2.8 it gives many functions to the developers to retrieve system path or URL whatever they want for their plugin. I prefer using the functions more than the constants. As they are really easy to use and gives the exact result and you don’t have to remember all the constants for making your plugin compatible with dynamic directory structure. So, lets start the discussion…

#0: The list of the useful Plugin directory and URL determining functions:

Here are all the functions useful for finding the plugin directory or url…

  • plugins_url: The most useful function to get the browser friendly URL of the plugin files.
  • plugin_dir_url: Get the URL of the plugin directory with a trailing slash.
  • plugin_dir_path: Server path of the plugin directory with a trailing slash.

Now lets see how to use them.

#1: plugins_url : Get URL of a file inside your plugin directory

Very useful if you want to get, say the URL of a JS or CSS file located inside your plugin directory. We normally use it to enqueue scripts or styles to wordpress. It returns you the URL of a file or directory.

#1.1: Parameters and source:

This is located in wp-includes/link-template.php and the source code is as follows:

/**
 * Retrieve the url to the plugins directory or to a specific file within that directory.
 * You can hardcode the plugin slug in $path or pass __FILE__ as a second argument to get the correct folder name.
 *
 * @package WordPress
 * @since 2.6.0
 *
 * @param string $path Optional. Path relative to the plugins url.
 * @param string $plugin Optional. The plugin file that you want to be relative to - i.e. pass in __FILE__
 * @return string Plugins url link with optional path appended.
*/
function plugins_url($path = '', $plugin = '') {

	$mu_plugin_dir = WPMU_PLUGIN_DIR;
	foreach ( array('path', 'plugin', 'mu_plugin_dir') as $var ) {
		$$var = str_replace('\\' ,'/', $$var); // sanitize for Win32 installs
		$$var = preg_replace('|/+|', '/', $$var);
	}

	if ( !empty($plugin) && 0 === strpos($plugin, $mu_plugin_dir) )
		$url = WPMU_PLUGIN_URL;
	else
		$url = WP_PLUGIN_URL;

	if ( 0 === strpos($url, 'http') && is_ssl() )
		$url = str_replace( 'http://', 'https://', $url );

	if ( !empty($plugin) && is_string($plugin) ) {
		$folder = dirname(plugin_basename($plugin));
		if ( '.' != $folder )
			$url .= '/' . ltrim($folder, '/');
	}

	if ( !empty($path) && is_string($path) && strpos($path, '..') === false )
		$url .= '/' . ltrim($path, '/');

	return apply_filters('plugins_url', $url, $path, $plugin);
}

It takes two parameters:

  • $path: (string) (Optional) The relative path of the file for which you want to find the URL. Say, you have a directory js inside your main plugin and have a file my_js.js inside it. To get the URL, you need to pass this parameter as $path=’js/my_js.js’.
  • $plugin: (string) (Optional) The server plugin path, about which you want to get the URL. In most of the cases, it is just the file. So, we pass in __FILE__. To access one level top directory, we can use dirname(__FILE__)

#1.2: Usage example:

Say, you want to enqueue a script file located inside another directory of your plugin. The directory structure is something like this:

You want to enqueue the jq-admin.js file inside the wordpress admin area. So, you pass in admin_init hook in a manner like this:

function adminaction_insert_js() {
	wp_enqueue_script('itg-admin-js', plugins_url('js/admin-jq.js', __FILE__), array('jquery'));
}
add_action('admin_init', 'adminaction_insert_js');

The add_actions hooks to admin_init where the script is put under the head section after loading jQuery. Note that we have used __FILE__ for the $plugin parameter. Because, this code is directory under the file wp-category-post-list.php at the root of your plugin directory. Now what if, say, you need to enqueue the script from the file wp-cpl-settings.php under the includes folder? Yes, you have guessed it right! We will use PHP dirname function to pass in the top level directory of the file. So the above code would change into something like this:

function wp_cpl_itg_adminaction_insert_js() {
	wp_enqueue_script('wp-cpl-itg-js', plugins_url('js/admin-jq.js', dirname(__FILE__)), array('jquery'));
}
add_action('admin_print_scripts-widgets.php', 'wp_cpl_itg_adminaction_insert_js');

Note: It can also return the URL of a directory, if you put say ‘js/’ on the $path parameter. But in such cases, using the following function is recommended.

#2: plugin_dir_url: Get URL of the directory of the plugin:

This is almost same as before, except that in can only retrieve the URL of a directory, not a file. Returns the URL of the plugin directory with a trailing slash.

#2.1: Parameters and source:

It is located under wp-includes/link-template.php and the source code is as follows:

/**
 * Gets the URL directory path (with trailing slash) for the plugin __FILE__ passed in
 * @package WordPress
 * @subpackage Plugin
 * @since 2.8
 *
 * @param string $file The filename of the plugin (__FILE__)
 * @return string the URL path of the directory that contains the plugin
 */
function plugin_dir_url( $file ) {
	return trailingslashit( plugins_url( '', $file ) );
}

It takes only one parameter:

  • $file: (string) The file name for which the directory URL is to be calculated. In most the cases if we want to find the directory URL of the current script, then we pass __FILE__

#2.2: Usage:

Almost same as before. If you use this API, then the previous example would change into something like this:

function wp_cpl_itg_adminaction_insert_js() {
	wp_enqueue_script('wp-cpl-itg-js', plugin_dir_path(__FILE__) . 'js/admin-jq.js', array('jquery'));
}
add_action('admin_print_scripts-widgets.php', 'wp_cpl_itg_adminaction_insert_js');

#3: plugin_dir_path Get Server path of the plugin directory:

This is very useful, if you want to include another PHP file, within you main Plugin PHP file. It returns the absolute server path of the plugin directory.

#3.1: Parameters and Source:

It is located under wp-includes/plugin.php and the source code is as follows:

/**
 * Gets the filesystem directory path (with trailing slash) for the plugin __FILE__ passed in
 * @package WordPress
 * @subpackage Plugin
 * @since 2.8
 *
 * @param string $file The filename of the plugin (__FILE__)
 * @return string the filesystem path of the directory that contains the plugin
 */
function plugin_dir_path( $file ) {
	return trailingslashit( dirname( $file ) );
}

It takes only one parameter:

  • $file: (string) The filename of the plugin whose absolute path is to be returned. Here also we use __FILE__ in most the cases.

#3.2: Usage and example:

Say, for the same plugin structure, you want to include the file wp-cpl-settings.php under includes/ directory to the file wp-category-post-list.php under the root directory of your plugin. What do is simple add this code to the wp-category-post-list.php file.

include_once(plugin_dir_path(__FILE__) . 'includes/wp-cpl-settings.php');

Easy right?

So, that was all about the plugin path and URL APIs of wordpress. Hope it will help you for your plugin development. If you are confused about something, feel free to ask us! And don’t forget to give your feedback.

4 comments

  1. Pingback: Tweets that mention Determine Plugin Directory and URL in WordPress using WP API -- Topsy.com

  2. Pingback: Add CSS Stylesheets only on Plugin/All pages Wordpress Admin | InTechgrity

  3. David

    To the web designer (you?)
    Great job with all the CSS3! Love it. It might be a bit overused, but it does look good. I definitely just changed a bit on my CSS3 button from your inspiration.

    Oh, and good article too 🙂
    Cheers!

  4. Pingback: http www intechgrity com determine plugin directory and… « Hamarasite.com

Comments are closed.