Wordpress: how to return value when using add_filter?

I have read WordPress code many times, but still don't understand how to return a value if more than one argument is 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 ); } 

There are 2 arguments in the filter above. When I add_filter , should I return 2 values ​​or just return the one I need? Is the following example correct if a name is needed?

 add_filter( 'bbp_get_topic_title', 'my_topic_title', 10, 2 ); function my_topic_title( $title, $topic_id ){ $title = 'my_example_title'; return $title; } 
+7
source share
1 answer

This is absolutely correct.

When registering a filter (or basically calling apply_filters ) you must call a function with at least two arguments β€” the name of the filter to apply and the value to which the filter will be applied.

Any additional arguments that you pass to the function will be passed to the filter functions, but only if they request additional arguments. Here is 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' ); 

Based on the code above, content to be filtered will be passed first to my_filtering_function1 . This function will only receive content to be filtered , not additional arguments.

Then the content will be transferred (after processing my_filtering_function1 ) to my_filtering_function2 . Again, the function will receive only the first argument.

Finally, the content will be passed to the my_filtering_function3 function (since it has been modified by the two previous functions). This time, the function will be passed instead of 2 arguments (since we indicated this), but it will not receive argument 3 .


See apply_filters() in the source .

+18
source

All Articles