功能:
add_filter函数用来挂载一个函数到指定的过滤器上。
用法:
参数:
$tag
(字符串)(必须)所挂载的过滤器名字(和目标 apply_filters() 函数的 $tag 属性一样)。
默认值:None
$function_to_add
(回调)(必须)要挂载的回调函数,参考 PHP 回调函数类型文档。
默认值:None
$priority
(整数)(可选)执行顺序,越小函数越先被执行。
默认值:10
$accepted_args
(整数)(可选)回调函数接收的参数数量,设置多个可以接收更多 apply_filters() 函数传进来的参数。
默认值:1
返回值:
(布尔)总是 True
所在位置:
add_filter()函数包含在 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' );
*
* Since WordPress 1.5.1, bound callbacks can take as many arguments as are
* passed as parameters in the corresponding apply_filters() call. The `$accepted_args`
* parameter allows for calling functions only when the number of args match.
*
* *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.
* @global array $merged_filters Tracks the tags that need to be merged for later. If the hook is added,
* it doesn't need to run through that process.
*
* @param string $tag The name of the filter to hook the $function_to_add callback to.
* @param callback $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 boolean true
*/
function add_filter( $tag, $function_to_add, $priority = 10, $accepted_args = 1 ) {
global $wp_filter, $merged_filters;
$idx = _wp_filter_build_unique_id($tag, $function_to_add, $priority);
$wp_filter[$tag][$priority][$idx] = array('function' => $function_to_add, 'accepted_args' => $accepted_args);
unset( $merged_filters[ $tag ] );
return true;
}
示例:
function test_func( $text, $var1, $var2 ){
return $text . $var1 . $var2;
}
add_filter( 'test', 'test_func', 10, 3 );
echo apply_filters( 'test', '参数2', '参数3', '参数4' );
相关函数:
apply_filters();
remove_filters();
感觉本站内容不错,读后有收获?小额赞助
还可以分享文章给好友: