WordPress:使用 add_filter 时如何返回值? [英] WordPress: How to return value when use add_filter?
问题描述
我已经多次阅读 WordPress codex,但仍然不明白如果涉及多个参数时如何返回值.例如:
I've read WordPress codex many times but still don't understand how to return the value if more than one arguments involved. For example:
function bbp_get_topic_title( $topic_id = 0 ) {
$topic_id = bbp_get_topic_id( $topic_id );
$title = get_the_title( $topic_id );
return apply_filters( 'bbp_get_topic_title', $title, $topic_id );
}
在上面的过滤器中,有 2 个参数.当我 add_filter
时,我应该返回 2 个值,还是只返回我需要的一个?如果需要标题,以下示例是否正确?
In the above filter, there are 2 arguments. When I add_filter
, should I return 2 value, or just return the one I need? Is the following example correct if need the title?
add_filter( 'bbp_get_topic_title', 'my_topic_title', 10, 2 );
function my_topic_title( $title, $topic_id ){
$title = 'my_example_title';
return $title;
}
推荐答案
完全正确.
在注册过滤器(或基本上调用 apply_filters
)时,您应该使用至少两个参数调用该函数 - 要应用的过滤器的名称和将应用过滤器的值.
When registering a filter(or basically calling apply_filters
), you should call the function with at least two arguments - name of the filter to be applied and the value to which the filter will be applied.
您传递给函数的任何其他参数都将传递给过滤函数,但仅如果它们请求了其他参数.举个例子:
Any further arguments that you pass to the function will be passed to the filtering functions, but only if they have requested additional arguments. Here's an example:
// Minimal usage for add_filter()
add_filter( 'my_filter', 'my_filtering_function1' );
// We added a priority for our filter - the default priority is 10
add_filter( 'my_filter', 'my_filtering_function2', 11 );
// Full usage of add_filter() - we set a priority for our function and add a number of accepted arguments.
add_filter( 'my_filter', 'my_filtering_function3', 12, 2 );
// Apply our custom filter
apply_filters( 'my_filter', 'content to be filtered', 'argument 2', 'argument 3' );
给定上面的代码,要过滤的内容
将首先传递给my_filtering_function1
.这个函数只会接收要过滤的内容
,而不是额外的参数.
Given the code above, the content to be filtered
will be passed first to my_filtering_function1
. This function will only receive the content to be filtered
and not the additional arguments.
然后将内容(经过my_filtering_function1
处理后)传递给my_filtering_function2
.同样,该函数将只接收第一个参数.
Then the content will then be passed(after being treated by my_filtering_function1
) to my_filtering_function2
. Again the function will only receive the first argument.
最后将内容传递给 my_filtering_function3
函数(因为它已被前两个函数更改).这次函数将改为传递 2 个参数(因为我们指定了这个),但它不会得到 argument 3
参数.
Finally the content will be passed to the my_filtering_function3
function(as it has been changed by the previous two functions). This time the function will be passed 2 arguments instead(since we specified this), but it won't get the argument 3
argument.
See apply_filters()
in source.
这篇关于WordPress:使用 add_filter 时如何返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!