Using WordPress ‘plugin_basename()’ PHP function

The plugin_basename() WordPress PHP function retrieves the basename of a plugin.

Usage

plugin_basename( $file )

Example:
Input: plugin_basename('/home/www/wp-content/plugins/wpdocs-plugin/wpdocs-plugin.php')
Output: wpdocs-plugin/wpdocs-plugin.php

Parameters

  • $file (string) - The filename of the plugin.

More information

See WordPress Developer Resources: plugin_basename

Examples

Get plugin basename

Retrieve the basename of the current plugin file.

$plugin_basename = plugin_basename(__FILE__);
echo $plugin_basename; // Outputs: "wpdocs-plugin/wpdocs-plugin.php"

Access plugin subdirectory

Access a subdirectory within the plugin, such as a "class" directory.

$class_dir = trailingslashit(dirname(plugin_basename(__FILE__))) . '/class';
echo $class_dir; // Outputs: "your-awesome-plugin/class"

Add a plugin action link using the callback action from another file or class.

In main plugin file:

if (!defined('WPDOCS_PLUGIN_BASE')) {
    define('WPDOCS_PLUGIN_BASE', plugin_basename(__FILE__));
}

In another file:

add_filter('plugin_action_links_' . WPDOCS_PLUGIN_BASE, 'wpdocs_plugin_settings_link');
function wpdocs_plugin_settings_link($links) {
    $row_meta = array(
        'settings' => '<a href="' . esc_attr(get_admin_url(null, 'admin.php?page=wpdocs-settings')) . '">' . __('Settings') . '</a>',
    );
    return array_merge($links, $row_meta);
}

Compare plugin_basename() and basename()

Compare the output of plugin_basename() and basename() for a plugin file.

$plugin_basename = plugin_basename(__FILE__);
$base_name = basename(__FILE__);

echo "plugin_basename: " . $plugin_basename . "\n"; // Outputs: "wpdocs-plugin/wpdocs-plugin.php"
echo "basename: " . $base_name; // Outputs: "wpdocs-plugin.php"

Get plugin directory

Retrieve the plugin directory name using plugin_basename().

$plugin_dir = dirname(plugin_basename(__FILE__));
echo $plugin_dir; // Outputs: "wpdocs-plugin"