How to check if which hook triggered the call to a function?

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 ;

}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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/

Method 2

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x