在WordPress中,程序在开发的时候作者就预留了一些过滤器钩子(Filter Hook),所有挂到过滤器钩子上的函数都是过滤器(Filters),add_filter()就是用来添加过滤器的。过滤器钩子它要做的是通过执行过滤器函数来改变对象或变量的值,就相当于对变量或者对象进行过滤或者处理。

过滤器可以提高了WordPress的灵活性,方便自定义开发。无论是制作WordPress主题还是WordPress插件,我们都会使用add_filter()添加过滤器来实现一些特殊需求。下面就详细的讲一下WordPress过滤器之add_filter() 。

1、add_filter()函数
add_filter()定义在wp-includes/plugin.php文件中,add_filter() 函数的源代码如下:

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;
}

2、add_filter()函数用法

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

$tag:必填(字符串)。挂载回调函数的过滤器名称。
$function_to_add:必填(可调用的函数)。过滤器应用时调用的回调函数。
$priority:可选(整型)。用于规定函数被执行的顺序,函数与特定动作关联。较小的数字匹配较早的执行,同等优先级的函数按加入action的顺序被执行。
$accepted_args:可选(整型)。add_filter() 过滤器可接受的参数个数,默认为1。

3、add_filter()函数实例

//定义过滤器函数custom_title,把所有的标题title修改为盛龙网络的博客
function custom_title($title) {
$title = '盛龙网络的博客';
return $title;
}
//把函数custom_title挂接到过滤器钩子wp_title上
add_filter('wp_title', 'custom_title');

发表回复

后才能评论