plugin_basename( string $file ): string
Gets the basename of a plugin.
Contents
Description
This method extracts the name of a plugin from its filename.
Parameters
-
$file
string Required -
The filename of plugin.
Return
string The name of a plugin.
More Information
This function gets the path to a plugin file or directory, relative to the plugins directory, without the leading and trailing slashes.
Uses both the WP_PLUGIN_DIR and WPMU_PLUGIN_DIR constants internally, to test for and strip the plugins directory path from the $file path. Note that the direct usage of WordPress internal constants is not recommended.
Source
File: wp-includes/plugin.php
.
View all references
function plugin_basename( $file ) {
global $wp_plugin_paths;
// $wp_plugin_paths contains normalized paths.
$file = wp_normalize_path( $file );
arsort( $wp_plugin_paths );
foreach ( $wp_plugin_paths as $dir => $realdir ) {
if ( str_starts_with( $file, $realdir ) ) {
$file = $dir . substr( $file, strlen( $realdir ) );
}
}
$plugin_dir = wp_normalize_path( WP_PLUGIN_DIR );
$mu_plugin_dir = wp_normalize_path( WPMU_PLUGIN_DIR );
// Get relative path from plugins directory.
$file = preg_replace( '#^' . preg_quote( $plugin_dir, '#' ) . '/|^' . preg_quote( $mu_plugin_dir, '#' ) . '/#', '', $file );
$file = trim( $file, '/' );
return $file;
}
Changelog
Version | Description |
---|---|
1.5.0 | Introduced. |
User Contributed Notes
You must log in before being able to contribute a note or feedback.
If your plugin file is located at /home/www/wp-content/plugins/wpdocs-plugin/wpdocs-plugin.php, and you call:
The
$x
variable will equal to “wpdocs-plugin/wpdocs-plugin.php”.Top ↑
Feedback
For a plugin that consist of just a PHP file (e.g.
wp-content/plugin.php
) and for a must-use plugin (e.g.wp-content/mu-plugins/plugin.php
),plugin_basename( __FILE__ )
returnsplugin.php
. Note that in these particular contexts,plugin_basename( __FILE__ )
andbasename( __FILE__ )
return the same value. However these functions are not equivalent for plugin files residing inside a subdirectory. — By Bart Kuijper —If you need to access a directory within your awesome plugin, eg, a class directory, you can access it by:
$lang_dir variable will now be “your-awesome-plugin/class”, you can now use this to reference files within the class directory.
If you want to add a plugin action link but need to use the callback action from another file or class than you can try this way
And now in other file you can easily use this contrast
so it is good practice to define a CONSTANT for
plugin_basename( __FILE__ )
and reuse it again.