Is this a good example of usage of current_filter()
?
<?php
add_filter("_my_filter", "common_function");
add_filter("_another_filter", "common_function");
function common_function(){
$currentFilter = current_filter();
switch ($currentFilter) {
case '_my_filter':
echo "Called by My Filter";
break;
case '_another_filter':
echo "Called by another filter";
break;
}
}
So I am guessing current_filter()
is used to get the name of the filter for which the current execution is happening?
2 Answers
Hi @Raj Sekharan:
Looks good to me, but is wanting to know the current usage really your question or do you want to understand where current_filter()
gets it’s information from?
If the latter, here’s basically what happens in all the different hook processing functions, e.g. do_action()
, apply_filters()
, do_action_ref_array()
, apply_filters_ref_array()
(greatly simplified, of course):
<?php
function <process_hook>($hook, $value) {
global $wp_filter, $wp_current_filter;
$wp_current_filter[] = $hook; // "Push" the hook onto the stack.
$value = call_user_func($wp_filter[$hook]['function'],$value);
array_pop($wp_current_filter);
return $value;
}
Then all that current_filter()
does is retrieve the last hook “pushed” onto the global wp_current_filter
array, i.e.:
<?php
function current_filter() {
global $wp_current_filter;
return end( $wp_current_filter );
}