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

概要

current_filterフィルタは、現在のフィルター(アクション)名を取得するための関数です。WordPressのテーマやプラグインの開発において、特定のフックが実行されているときに、それに関連する処理を行いたい場合によく用いられます。このフィルターは、以下のシチュエーションで頻繁に使用されます。

  1. 特定のアクションフック内での条件分岐を行う場合
  2. フィルター処理をデバッグする際
  3. 他のプラグインとの互換性をチェックする場合
  4. フックに応じて異なる動作を設定する場合
  5. 特定のコンテキストでのみコードを実行したい場合
  6. フックの再利用における情報を取得する場合
  7. ロギング目的でフック名を記録する場合
  8. フックによる機能拡張を行う場合

構文

$current_filter = current_filter();

パラメータ

このフィルタは特定のパラメータを持ちません。

戻り値

現在のフィルター名を示す文字列を返します。

関連する関数

https://refwp.com/?titleonly=1&s=current_filter

使用可能なバージョン

このフィルタは、WordPressのバージョン2.8以降で使用可能です。

コアファイルのパス

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_filter('example_filter', function() {
    echo 'Current filter: ' . current_filter();
});

引用元: https://developer.wordpress.org/reference/functions/current_filter/

サンプルコード2: 特定のフィルターの下で条件分岐

特定のフィルターに対して処理を実行するコードの例です。

add_filter('wp_head', function() {
    if (current_filter() === 'wp_head') {
        // wp_head の処理
    }
});

引用元: https://developer.wordpress.org/reference/functions/current_filter/

サンプルコード3: フィルターでのデバッグ情報出力

デバッグ用に現在のフィルター名をログに出力するコードです。

add_filter('the_content', function($content) {
    error_log('Current filter: ' . current_filter());
    return $content;
});

引用元: https://developer.wordpress.org/reference/functions/current_filter/

サンプルコード4: 他のプラグインとの互換性の確認

他のプラグインとの互換性のために現在のフィルターを確認する例です。

add_action('plugins_loaded', function() {
    if (current_filter() === 'plugins_loaded') {
        // プラグインが読み込まれた後の処理
    }
});

引用元: https://developer.wordpress.org/reference/functions/current_filter/

サンプルコード5: フック名による区別

異なるフックに対して異なる動作をする場合のサンプルです。

add_action('wp', function() {
    switch (current_filter()) {
        case 'wp':
            // wpの処理
            break;
        default:
            break;
    }
});

引用元: https://developer.wordpress.org/reference/functions/current_filter/

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


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