How to check if which hook triggered the call to a function?
Question
I have a situation where I have a function hooked to more than one custom hooks. How to check in the callback function which custom hook triggered the call?
Or the question in code will be
add_action('my_test_hook_1','my_test_callback_function');
add_action('my_test_hook_2','my_test_callback_function');
add_action('my_test_hook_3','my_test_callback_function');
add_action('my_test_hook_4','my_test_callback_function');
function my_test_callback_function(){
$called_action_hook = ; //Some magic code that will return current called action the hook
echo "This function is called by action: " . $called_action_hook ;
}
Solution
I found the magic code you need.
Use current_filter()
. This function will return name of the current filter or action.
add_action('my_test_hook_1','my_test_callback_function');
add_action('my_test_hook_2','my_test_callback_function');
add_action('my_test_hook_3','my_test_callback_function');
add_action('my_test_hook_4','my_test_callback_function');
function my_test_callback_function(){
$called_action_hook = current_filter(); // ***The magic code that will return the last called action
echo "This function is called by action: " . $called_action_hook ;
}
For reference: https://developer.wordpress.org/reference/functions/current_filter/
OTHER TIPS
The solution will be to add a parameter to do_action
and then pick that up in your add_action
function:
add_action('my_test_hook_1','my_test_callback_function');
add_action('my_test_hook_2','my_test_callback_function');
add_action('my_test_hook_3','my_test_callback_function');
add_action('my_test_hook_4','my_test_callback_function');
function my_test_callback_function( $called_action_hook ){
echo "This function is called by action: " . $called_action_hook ;
}
do_action('my_test_hook_1','my_test_hook_1');
do_action('my_test_hook_2','my_test_hook_2');
etc.
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange