I am not able to understand a very logic behind add_action / add_filter
Consider following example:
function SearchFilter($query) {
if ($query->is_search) {
$query->set('post_type', 'page');
}
return $query;
}
add_filter('pre_get_posts','SearchFilter');
My questions are
-
How can I know wheter function ‘SearchFilter’ accepts any argument or
not? -
What will be that argument / what will be it’s type?
-
How can I determine for which action/filter there is any argument?
-
Should every action / filter return the passed parameter?
When calling an action hook using
The callback function is called when a
do_action()
call is fired with the corresponding tag for example:And when calling a filter hook using:
The callback function is called when a
apply_filters()
call is fired with the corresponding tag for example:Now as you can see the main difference is that the action hook basically lets you run your own function at a given point,, and a filter hook lets you filter (change/alter/clean …) the value of a specific variable.
So an action “hooked” callback_function accepts arguments only if any were specified and a filter “hooked” callback_function accepts at least one argument which is the value to alter itself and more arguments only if specified.
As for you questions
The hooked function (in this case SearchFilter) accepts whatever arguments that the hook trigger (either apply_filters() for filter hooks or do_action() for action hooks) is passing to it and the best way to know what they are is to search the code for the hook tag (e.g searchFilter) and see what they are.
However as stated above since we you are hooking it to a filter hook it will have at least one argument.
Same as above you can see that in the hook trigger function or by creating a test dump which would be something like this?
Action hooks doesn’t expect a return value so no, but a filter hook should return a value almost every time.
The best way I know of to get args is to look up the do_action call for the hook you’re using in the code. adambrown.info has a great section on this. Here’s the one you’ll need.