Using WordPress ‘plugin_dir_path()’ PHP function

The plugin_dir_path() WordPress PHP function retrieves the filesystem directory path (with trailing slash) for the plugin FILE passed in.

Usage

plugin_dir_path( $file );

Custom example:

$plugin_directory = plugin_dir_path( __FILE__ );

Output:

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

Parameters

  • $file (string) (Required): The filename of the plugin (FILE).

More information

See WordPress Developer Resources: plugin_dir_path()

Examples

Include PHP files from a plugin subfolder

This example includes all PHP files from a plugin subfolder named ‘subfolder’:

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

Get the parent directory path

This example retrieves the parent directory path of the plugin directory:

$parent_directory = plugin_dir_path( __DIR__ );

Define a path constant

This example defines a constant for the plugin directory path and includes multiple files:

define( 'MY_PLUGIN_PATH', plugin_dir_path( __FILE__ ) );
include( MY_PLUGIN_PATH . 'includes/admin-page.php');
include( MY_PLUGIN_PATH . 'includes/classes.php');

Conditionally load files

This example loads admin functions if in the admin area, and front-end functions otherwise:

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' );
}

Define constants for path and URL

This example defines constants for the plugin base path and assets URL, and uses them to include files and load assets:

define( 'PREFIX_BASE_PATH', plugin_dir_path( __FILE__ ) );
define( 'PREFIX_ASSETS_URL', plugins_url( '/assets', __FILE__ ) );

include( PREFIX_BASE_PATH . 'inc/init.php' );
wp_register_style( 'prefix_library', PREFIX_ASSETS_URL . '/dir/lib.css' );