plugin_dir_path()
Gets the full path to the folder where the specified file - __FILE__ is located. With a slash at the end.
Can be used to obtain the full system path to the directory of any file. It does not necessarily have to be a plugin file.
The function is created for convenient use of the construct:
trailingslashit( __DIR__ );
Use the constant WP_PLUGIN_DIR to get the path to the folder with all plugins.
plugin_dir_url(__FILE__) — a similar function to get the URL of the plugin folder.
No Hooks.
Returns
String. The full path in the system to the directory where the specified file is located.
Usage
plugin_dir_path( $file );
- $file(string) (required)
- The full path to the file. Usually uses the magic constant
__FILE__.
Examples
#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.
#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;
} #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/
#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' );
#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() plugin dir path code WP 6.9.1
function plugin_dir_path( $file ) {
return trailingslashit( dirname( $file ) );
}