ワードプレスのcurrent_actionフィルタの使用方法・解説

概要

current_action フィルタは、WordPress のアクションフックの中で現在のアクション名を取得するために使用されます。このフィルタは、特定の処理を行う際に、どのアクションフックが現在実行されているかを確認するのに役立ちます。以下のような機能を実装する際によく使用されます:

  1. アクションごとのカスタム処理
  2. フィルタリング条件の基準としての使用
  3. デバッグ情報の表示
  4. テーマやプラグインの設定に条件を設ける
  5. ログ出力のカスタマイズ
  6. イベントのトリガー管理
  7. 削除や変更が必要な場合のフック管理
  8. 特定の条件下でのスクリプトやスタイルの読み込み制御

構文

$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 アクションで現在のアクション名をフッターに表示します。

この関数について質問する


上の計算式の答えを入力してください