挂钩函数永远不会覆盖使用相同操作或过滤器挂钩的其他挂钩函数.
它们被添加到一种“挂钩队列”基于优先级规则的执行顺序:
- 如果指定了优先级,它们将首先按钩子优先级和声明优先级在队列中排序。
- 如果没有指定优先级,则它们采用默认优先级 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() or 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>';
}
您可能已经注意到,有两种钩子,即过滤器钩子和操作钩子。
-
动作挂钩:
-
动作钩子执行点 (扳机): with do_action()
-
将函数附加到动作挂钩 (已触发): with add_action():函数被执行并且可以有可选参数。
-
过滤钩:
-
过滤器钩子执行点 (扳机): with apply_filters()
-
将函数附加到过滤器挂钩 (过滤/触发): with add_filter(): 强制参数(一个变量)被过滤并从“hooked”函数返回
挂钩及其挂钩函数可以位于任何位置,例如在 function.php 文件中你活跃的孩子主题 (或活动主题)以及在任何pluginsphp 文件。
Related:
- WooCommerce 操作挂钩和覆盖模板
- 如何将自定义挂钩添加到 Woocommerce 的自定义插件
- WordPress:过滤器和操作挂钩之间的区别?