SYNCER

SYNCER

add_filter() - フィルターイベントと関数を紐付ける

公開日:

add_filter()は、指定したフィルターイベントと関数を紐付ける関数です。紐付けることによって、フィルターイベントが発火した時に、目的の関数が実行されます。

構文

bool add_filter( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 )

パラメータ

$tag

イベントの名前。

$function_to_add

コールバック関数。関数の名前を指定する。無名関数を直接指定してもいい。

$priority

初期値: 10

優先順位。フィルターに複数の関数が紐付けられている場合、この数値が低いほど先に実行される。同じ優先順位の場合は、先に紐付けられた関数が、先に実行される。

$accepted_args

初期値: 1

受け取る引数の数。

返り値

bool

必ずtrueが返る。

関数

この関数内で利用している、別のWordPress関数です。

  • newWP_Hook()

サンプルコード

フィルターイベントに関数を紐付ける

関数を紐付けることによって、その関数がフィルターイベント発火時のコールバック関数となります。ここでは、_hogeというフィルターに、_fireという名前の関数を紐付けました。

php

<?php
// 関数の内容
function _fire ( $data ) {
	echo "発火しました。" ;
}

// フィルターに関数を紐付ける
add_filter( '_hoge', '_fire' );

// '_hoge'というフィルターイベントを発火
apply_filters( '_hoge', "ABC" ) ;

結果 (出力内容) - PHP7.0.13

発火しました。

優先順位を指定する

同じフィルターイベントに複数のイベントを紐付ける時、第3引数で優先順位を指定できます。例えば下記では、aaa()bbb()の順番で実行されるように紐付けました。"AAA"というデータがaaa()を経て"AAABBB"、次にbbb()を経て"AAABBBCCC"と加工されました。

php

<?php
// 関数の内容
function aaa ( $data ) {
	return $data . "BBB" ;
}

function bbb ( $data ) {
	return $data . "CCC" ;
}

// フィルターに関数を紐付ける
add_filter( '_hoge', 'aaa', 11 );
add_filter( '_hoge', 'bbb', 12 );

// '_hoge'というフィルターイベントを発火
$result = apply_filters( '_hoge', "AAA" ) ;

// 結果
var_dump( $result ) ;

結果 (出力内容) - PHP7.0.13

string(9) "AAABBBCCC"

デフォルトでは補助的な引数は受け取れない

デフォルトではコールバック関数は、第1引数(加工する値そのもの)しか受け取れません。例えば下記を試してみて下さい。

php

<?php
// 関数の内容
function _fire ( $data, $arg1=null, $arg2=null ) {
	echo '$arg1: ' . $arg1 . "\n" ;
	echo '$arg2: ' . $arg2 . "\n" ;
}

// フィルターに関数を紐付ける
add_filter( '_hoge', '_fire' );

// '_hoge'というフィルターイベントを発火
apply_filters( '_hoge', "AAA", "補助情報1", "補助情報2" ) ;

結果 (出力内容) - PHP7.0.13

$arg1: 
$arg2:

受け取る引数の数を指定する

コールバック関数が第2引数以降を受け取るには、第4引数で受け取る引数の数を指定しなければいけません。先ほどと同じ内容ですが、今度は第4引数を指定してみました。

php

<?php
// 関数の内容
function _fire ( $data, $arg1=null, $arg2=null ) {
	echo '$arg1: ' . $arg1 . "\n" ;
	echo '$arg2: ' . $arg2 . "\n" ;
}

// フィルターに関数を紐付ける
add_filter( '_hoge', '_fire', 10, 3 );

// '_hoge'というフィルターイベントを発火
apply_filters( '_hoge', "AAA", "補助情報1", "補助情報2" ) ;

結果 (出力内容) - PHP7.0.13

$arg1: 補助情報1
$arg2: 補助情報2

無名関数を紐付ける

関数名でなく、無名関数を指定できます。

php

<?php
// フィルターに無名関数を紐付ける
add_filter( '_hoge', function ( $data ) {
	// データを加工する
	return $data . "DEF" ;
} );

// 実行
$result = apply_filters( '_hoge', "ABC" ) ;

// 結果
var_dump( $result ) ;

結果 (出力内容) - PHP7.0.13

string(6) "ABCDEF"

ソースコード

wp-includes/plugin.php

/**
 * Hook a function or method to a specific filter action.
 *
 * WordPress offers filter hooks to allow plugins to modify
 * various types of internal data at runtime.
 *
 * A plugin can modify data by binding a callback to a filter hook. When the filter
 * is later applied, each bound callback is run in order of priority, and given
 * the opportunity to modify a value by returning a new value.
 *
 * The following example shows how a callback function is bound to a filter hook.
 *
 * Note that `$example` is passed to the callback, (maybe) modified, then returned:
 *
 *     function example_callback( $example ) {
 *         // Maybe modify $example in some way.
 *         return $example;
 *     }
 *     add_filter( 'example_filter', 'example_callback' );
 *
 * Bound callbacks can accept from none to the total number of arguments passed as parameters
 * in the corresponding apply_filters() call.
 *
 * In other words, if an apply_filters() call passes four total arguments, callbacks bound to
 * it can accept none (the same as 1) of the arguments or up to four. The important part is that
 * the `$accepted_args` value must reflect the number of arguments the bound callback *actually*
 * opted to accept. If no arguments were accepted by the callback that is considered to be the
 * same as accepting 1 argument. For example:
 *
 *     // Filter call.
 *     $value = apply_filters( 'hook', $value, $arg2, $arg3 );
 *
 *     // Accepting zero/one arguments.
 *     function example_callback() {
 *         ...
 *         return 'some value';
 *     }
 *     add_filter( 'hook', 'example_callback' ); // Where $priority is default 10, $accepted_args is default 1.
 *
 *     // Accepting two arguments (three possible).
 *     function example_callback( $value, $arg2 ) {
 *         ...
 *         return $maybe_modified_value;
 *     }
 *     add_filter( 'hook', 'example_callback', 10, 2 ); // Where $priority is 10, $accepted_args is 2.
 *
 * *Note:* The function will return true whether or not the callback is valid.
 * It is up to you to take care. This is done for optimization purposes, so
 * everything is as quick as possible.
 *
 * @since 0.71
 *
 * @global array $wp_filter      A multidimensional array of all hooks and the callbacks hooked to them.
 *
 * @param string   $tag             The name of the filter to hook the $function_to_add callback to.
 * @param callable $function_to_add The callback to be run when the filter is applied.
 * @param int      $priority        Optional. Used to specify the order in which the functions
 *                                  associated with a particular action are executed. Default 10.
 *                                  Lower numbers correspond with earlier execution,
 *                                  and functions with the same priority are executed
 *                                  in the order in which they were added to the action.
 * @param int      $accepted_args   Optional. The number of arguments the function accepts. Default 1.
 * @return true
 */
function add_filter( $tag, $function_to_add, $priority = 10, $accepted_args = 1 ) {
	global $wp_filter;
	if ( ! isset( $wp_filter[ $tag ] ) ) {
		$wp_filter[ $tag ] = new WP_Hook();
	}
	$wp_filter[ $tag ]->add_filter( $tag, $function_to_add, $priority, $accepted_args );
	return true;
}

参考リンク