Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
913 views
in Technique[技术] by (71.8m points)

add filter - WordPress: How to return value when use add_filter?

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

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That's absolutely correct.

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' );

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.

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...