如何检查是哪个钩子触发了对函数的调用?

时间:2021-02-25 作者:ABHi

我有一种情况,我有一个连接到多个自定义挂钩的函数。如何检入回调函数哪个自定义挂钩触发了调用?

否则代码中的问题将是

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 ;

}

2 个回复
最合适的回答,由SO网友:Akshay Kumar S 整理而成

我找到了你需要的魔法密码。

使用current_filter(). 此函数将返回当前筛选器或操作的名称。

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 ;

}
供参考:https://developer.wordpress.org/reference/functions/current_filter/

SO网友:Coder At Heart

解决方案是在do_action 然后在你的add_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 ){
    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. 

相关推荐

Conditional action hooks

我正在开发一个使用AJAX的插件,但我在控制代码流方面遇到了困难。我想在运行条件后挂接函数。我的钩子在控制结构内部添加时不会启动,但在外部会启动。我还有一个触发AJAX请求的事件,这只能在用户点击触发事件后,在加载所有DOM之后发生。AJAX请求告诉PHP函数设置cookie。它设置了cookie,但在阅读关于cookie的PHP文档时,我发现它们只能在发送任何输出后设置,但我还是做到了这一点?我读过WordPress初始化序列,但这并没有帮助我解决这个问题。这是我的密码:add_action(\'wp_