首页 WordPress函数大全 add_filter()

add_filter()

2020-05-02 / 6117阅 / 悠然

如何你看完本文还不知道如何使用该函数,可以联系我定制视频教程,50元/个函数,学不会全额退款

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

将函数或方法挂接到特定的过滤器操作。

描述

WordPress提供了过滤器挂钩,以允许插件在运行时修改各种类型的内部数据。

插件可以通过将回调绑定到过滤器挂钩来修改数据。稍后应用过滤器时,将按优先级顺序运行每个绑定的回调,并有机会通过返回新值来修改值。

以下示例显示了如何将回调函数绑定到过滤器挂钩。

请注意,将$ example传递给回调,(可能)对其进行了修改,然后返回:

函数example_callback($ example){
    //也许以某种方式修改$ example。
    返回$ example;
}
add_filter('example_filter','example_callback');  

绑定的回调可以接受从不
接受到相应的apply_filters()调用中作为参数传递的参数总数。

换句话说,如果apply_filters()调用总共传递了四个参数,则绑定到
该参数的回调可以不接受任何参数(与1相同)或最多接受四个参数。重要的是,
$ accepted_args值必须反映绑定回调实际
选择接受的参数数量。如果回调没有接受任何参数,则认为
与接受1个参数相同。例如:

//过滤调用。
$ value = https://developer.wordpress.org/reference/functions/add_filter/apply_filters('hook',$ value,$ arg2,$ arg3);

//接受零/一参数。
函数example_callback(){
    ...
    返回“一些价值”;
}
add_filter('hook','example_callback'); //其中$ priority默认为10,$ accepted_args默认为1。

//接受两个参数(三个可能)。
函数example_callback($ value,$ arg2){
    ...
    返回$ maybe_modified_value;
}
add_filter('hook','example_callback',10,2); //其中$ priority为10,$ accepted_args为2。 

_注意:_无论回调是否有效,该函数都将返回true。请您自己保重。这样做是出于优化目的,因此一切都尽可能快。

参数

$tag

(string)
(Required)
The name of the filter to hook the $function_to_add callback to.

$function_to_add

(callable)
(Required)
The callback to be run when the filter is applied.

$priority

(int)
(Optional)
Used to specify the order in which the functions associated with a particular action are executed. 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.

Default value: 10

$accepted_args

(int)
(Optional)
The number of arguments the function accepts.

Default value: 1

返回

(true)

大家谈论
    我的见解