plugin_dir_path()WP 2.8.0

Get the filesystem directory path (with trailing slash) for the plugin __FILE__ passed in.

1 time — 0.000024 sec (very fast) | 50000 times — 0.08 sec (speed of light)

No Hooks.

Return

String. the filesystem path of the directory that contains the plugin.

Usage

plugin_dir_path( $file );
$file(string) (required)
The filename of the plugin (__FILE__).

Examples

0

#1 Get the directory of the current file

It is assumed that the function is called from a plugin file called my-plugin:

$dir = plugin_dir_path( __FILE__ );
echo $dir;

// Get:
// /home/user/var/www/wordpress/wp-content/plugins/my-plugin/

The example comment refers to the return value if the code is called from the root of the my-plugin.

0

#2 Connect all PHP files from the plugin subdirectory

Include all PHP files from the subfolder folder of the current plugin.

foreach( glob( plugin_dir_path( __FILE__ )."subfolder/*.php" ) as $file ){
	include_once $file;
}
0

#3 Get the system path to the directory of all plugins

In general, the path to the plugins directory is in the WP_PLUGIN_DIR constant, but you can also get it with this function:

//current path: /home/www/site.com/wp-content/plugins/my-plugin/

$dir = plugin_dir_path( __DIR__ );
//$dir is set to /home/www/site.com/wp-content/plugins/
0

#4 Create a constant for the plugin's path and URL

It is often convenient to create a constant for a plugin that contains the plugin's path and then use that constant everywhere in the plugin's code.

It is customary to create such a constant in the main plugin file.

// The path to the plugin folder with a slash at the end
define( 'MY_PLUGIN_PATH', plugin_dir_path( __FILE__ ) );

// use the constant anywhere in the code
require_once MY_PLUGIN_PATH . 'includes/admin-page.php';
require_once MY_PLUGIN_PATH . 'includes/classes.php';
// etc.

The same maner we can create a URL to the main plugin direcrory:

define( 'MY_PLUGIN_URL', plugins_url( '', __FILE__ ) );

// now use in like so:
wp_register_style( 'some-lib', MY_PLUGIN_URL . '/dir/lib.css' );
0

#5 Connecting files by condition

If you want to connect different files, for example, for the admin panel and for the front-end, you can use this condition:

if ( is_admin() ) {
	include_once plugin_dir_path( __FILE__ ) . 'includes/admin-functions.php';
}
else {
	include_once plugin_dir_path( __FILE__ ) . 'includes/front-end-functions.php';
}

Changelog

Since 2.8.0 Introduced.

plugin_dir_path() code WP 6.4.3

function plugin_dir_path( $file ) {
	return trailingslashit( dirname( $file ) );
}