plugin_basename()WP 1.5.0

Gets the basename of a plugin.

This method extracts the name of a plugin from its filename.

1 time — 0.0000212 sec (very fast) | 50000 times — 0.17 sec (very fast) | PHP 7.4.33, WP 6.2.2

No Hooks.

Return

String. The name of a plugin.

Usage

plugin_basename( $file );
$file(string) (required)
The filename of plugin.

Examples

0

#1 Demo: get plugin basic name - folder_name/main_file.php

Suppose the plugin file is in this path: /home/www/wp-content/plugins/my-plugin/my-plugin.php
then by calling plugin_basename we get the following:

$plug_basename = plugin_basename( __FILE__ ); // my-plugin/my-plugin.php
Note if plugin consist of one PHP file and lies directly in plugins folder.

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__ ) returns plugin.php.

Notes

  • Global. Array. $wp_plugin_paths

Changelog

Since 1.5.0 Introduced.

plugin_basename() code WP 6.5.4

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