钩子函数永远不会覆盖使用相同操作或过滤钩子的其他钩子函数。
它们被添加到一种“挂钩队列”中,执行顺序基于优先级规则:
- 如果指定了优先级,它们将首先按挂钩优先级和声明优先级在队列中排序。
- 如果没有指定优先级,则默认优先级为 10,并通过声明在队列中排序。
所以你可以在同一个钩子上拥有许多钩子函数,例如在 Woocommerce 模板文件中content-single-product.php
图解示例:
在下面的注释代码示例中,您可以看到woocommerce_thankyou
动作挂钩的每个挂钩函数在挂钩队列中的执行顺序:
// No defined priority (default priority is 10)
add_action( 'woocommerce_thankyou', 'first_custom_function_no_priority' );
function first_custom_function_no_priority( $order_id ) {
// ==> Triggered in third position ==> [3]
}
## Default Hook "woocommerce_order_details_table" (default priority is 10)
// ==> Triggered in second position ==> [2]
// Defined priority is 10
add_action( 'woocommerce_thankyou', 'order_created_get_skus', 10 );
function order_created_get_skus( $order_id ) {
// ==> Triggered in Fourth position ==> [4]
}
// Defined priority is 5
add_action( 'woocommerce_thankyou', 'third_custom_function', 5 );
function third_custom_function( $order_id ) {
// ==> Triggered in first position ==> [1]
}
// Defined priority is 20
add_action( 'woocommerce_thankyou', 'fourth_custom_function', 20 );
function fourth_custom_function( $order_id ) {
// ==> Triggered at last (sixth) ==> [6]
}
// No defined priority (default priority is 10)
add_action( 'woocommerce_thankyou', 'last_custom_function_no_priority' );
function last_custom_function_no_priority( $order_id ) {
// ==> Triggered in fifth position ==> [5]
}
较低优先级在之前执行(或触发),较高优先级在之后执行(或触发)。如果未指定优先级,则默认优先级为 10。
挂钩函数只能通过强制定义的优先级remove_action()
或remove_filter()
使用强制定义的优先级来删除。
要查看具有所有必要细节的特定挂钩上挂钩了多少挂钩函数,您可以使用以下将为您提供原始输出的内容:
global $wp_filter;
// HERE below you define the targeted hook name
$hook_name = 'woocommerce_widget_shopping_cart_buttons';
if( isset($wp_filter[$hook_name]) ) {
echo '<pre>';
print_r($wp_filter[$hook_name]);
echo '</pre>';
} else {
echo '<p>Hook "'.$hook_name.'" is not used yet!</p>';
}
正如您所注意到的,有两种钩子,它们是过滤器钩子和动作钩子。
动作挂钩:
过滤钩:
钩子和它们的钩子函数可以位于任何位置,例如在您的活动子主题 (或活动主题)的 function.php 文件中,也可以在任何插件php 文件中。
有关的: