概要
plugin_basename
関数は、WordPressのプラグインのベース名を取得するための関数です。この関数は主にプラグインの管理や設定、情報取得に関連する場面でよく使用されます。
よく使われる機能実装
- プラグインの情報を取得
- プラグインの設定ページを作成
- プラグインのアクティベーションとデアクティベーション処理
- プラグインの差分更新処理
- サブメニューにプラグイン名を表示
- プラグインのバージョン管理
- 他のプラグインとの互換性チェック
- プラグインのリソースファイルの読み込み
構文
string plugin_basename( string $file )
パラメータ
$file
(string): プラグインのファイルパス(フルパスなど)。
戻り値
- (string): プラグインのベース名。
関連する関数
使用可能なバージョン
- WordPress 1.5.0 以降
コアファイルのパス
wp-includes/plugin.php
サンプルコード
サンプル1: プラグインのベース名を取得
このサンプルコードは、プラグインのフルパスからベース名を取得して表示します。
$file = __FILE__;
$basename = plugin_basename($file);
echo $basename; // 結果: プラグインのベース名を表示
引用元: https://developer.wordpress.org/reference/functions/plugin_basename/
サンプル2: プラグイン名をサブメニューに追加
このサンプルは、プラグインのベース名を元にサブメニューを追加する例です。
add_action('admin_menu', 'my_plugin_menu');
function my_plugin_menu() {
add_submenu_page(
'options-general.php',
'My Plugin Settings',
'My Plugin',
'manage_options',
plugin_basename(__FILE__),
'my_plugin_settings_page'
);
}
引用元: https://developer.wordpress.org/reference/functions/add_submenu_page/
サンプル3: プラグインのアクティベーションフック
このサンプルは、プラグインがアクティベートされたときにベース名を使ってログを取る例です。
register_activation_hook(__FILE__, 'my_plugin_activation');
function my_plugin_activation() {
$basename = plugin_basename(__FILE__);
error_log("Activating plugin: $basename");
}
引用元: https://developer.wordpress.org/reference/functions/register_activation_hook/
サンプル4: 他プラグインとの互換性チェック
このサンプルは、他のプラグインとの互換性を確認するためにベース名を使用する例です。
if (!is_plugin_active(plugin_basename('other-plugin-folder/other-plugin.php'))) {
// 他のプラグインが無効の場合の処理
}
引用元: https://developer.wordpress.org/reference/functions/is_plugin_active/
サンプル5: プラグインの設定を表示
このサンプルは、プラグインの設定ページでベース名を使って情報を表示する例です。
function my_plugin_settings_page() {
$basename = plugin_basename(__FILE__);
echo "<h1>Settings for $basename</h1>";
// 残りの設定表示処理…
}
引用元: https://developer.wordpress.org/reference/functions/admin_menu/
この関数のアクションでの使用可能性
アクション | 使用可能性 |
---|---|
mu_plugin_loaded | |
registered_post_type | |
plugins_loaded | 〇 |
wp_roles_init | |
setup_theme | |
after_setup_theme | |
set_current_user | |
init | |
register_sidebar | |
wp_loaded | |
send_headers | |
parse_query | |
pre_get_posts | |
wp | |
template_redirect | |
get_header | |
wp_head |
非推奨または削除されたバージョン
- 該当なし。