-

WordPress过滤器之add_filter()

PHP

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() 函数的源代码如下:
[cc lang=”php”]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;
}[/cc]

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

3、add_filter()函数实例
[cc lang=”php”]//定义过滤器函数custom_title,把所有的标题title修改为雷雪松的博客
function custom_title($title) {
$title = ‘雷雪松的博客’;
return $title;
}
//把函数custom_title挂接到过滤器钩子wp_title上
add_filter(‘wp_title’, ‘custom_title’);[/cc]

来源:WordPress过滤器之add_filter()

WordPress过滤器之add_filter()” 评论

    好听的名字 评论:
    2022年7月3日 下午3:35

    不错支持

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注