概要
current_action
フィルタは、WordPress のアクションフックの中で現在のアクション名を取得するために使用されます。このフィルタは、特定の処理を行う際に、どのアクションフックが現在実行されているかを確認するのに役立ちます。以下のような機能を実装する際によく使用されます:
- アクションごとのカスタム処理
- フィルタリング条件の基準としての使用
- デバッグ情報の表示
- テーマやプラグインの設定に条件を設ける
- ログ出力のカスタマイズ
- イベントのトリガー管理
- 削除や変更が必要な場合のフック管理
- 特定の条件下でのスクリプトやスタイルの読み込み制御
構文
$current_action = apply_filters('current_action', $hook);
パラメータ
$hook
(string) : 現在のアクションフック名。
戻り値
- (string) : フィルタリングされたアクション名。
関連する関数
https://refwp.com/?titleonly=1&s=current_action
使用可能なバージョン
WordPress 2.0.0 以降で利用可能です。
コアファイルのパス
wp-includes/plugin.php
この関数のアクションでの使用可能性
アクション名 | 使用例 |
---|---|
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 |
サンプルコード
サンプルコード1: カスタムログ出力
add_action('init', function() {
$current_action = apply_filters('current_action', 'init');
error_log('Current action is: ' . $current_action);
});
このコードは、init
アクションが実行されると、現在のアクション名をログに出力します。
サンプルコード2: 特定のアクションに対する処理の追加
add_action('wp_head', function() {
$current_action = apply_filters('current_action', 'wp_head');
if ($current_action === 'wp_head') {
echo '<!-- Custom Header Output -->';
}
});
このコードは、wp_head
アクションでカスタム HTML コメントを出力します。
サンプルコード3: 他のアクションでの条件付き実行
add_action('template_redirect', function() {
$current_action = apply_filters('current_action', 'template_redirect');
if ($current_action === 'template_redirect') {
// Do something specific for template_redirect
}
});
このコードは、template_redirect
アクションに対して特定の処理を行います。
サンプルコード4: カスタムスクリプトのエンキュー
add_action('wp_enqueue_scripts', function() {
$current_action = apply_filters('current_action', 'wp_enqueue_scripts');
if ($current_action === 'wp_enqueue_scripts') {
wp_enqueue_script('custom-script', get_template_directory_uri() . '/js/custom-script.js');
}
});
このコードは、wp_enqueue_scripts
アクションでカスタムスクリプトを読み込みます。
サンプルコード5: フィルタリングされたアクションを表示
add_action('wp_footer', function() {
$current_action = apply_filters('current_action', 'wp_footer');
echo '<p>Current action: ' . esc_html($current_action) . '</p>';
});
このコードは、wp_footer
アクションで現在のアクション名をフッターに表示します。