前两天学习了 add_filters() 函数,详见>>> WordPress学习——add_filter()详解 ,今天趁热打铁再来学习下它的使用。一般情况下 add_filters() 有两种方式触发,一种是当程序运行到特定时候 WordPress 程序会判断用户是否对某些参数做了新的定义,如果有则优先使用用户的设置;另一种方式是,用户可以直接通过 apply_filters() 函数直接调用。代码示例如下:
// 预定义的过滤器回调函数
function example_callback( $string, $arg1, $arg2 ) {
// (maybe) modify $string
return $string;
}
add_filter( 'example_filter', 'example_callback', 10, 3 );
// 通过 apply_filters() 传参调用定义好的过滤器回调函数
$value = apply_filters( 'example_filter', 'filter me', $arg1, $arg2 );
apply_filters() 有两个固定参数以及其他我们需要传递给过滤器回调函数的参数,其调用方法如下所示:
apply_filters( string $tag, mixed $value,$var,... )
$tag