2

我是 Wordpress/WooCommerce 和 PHP 的新手,虽然我有其他网络平台和语言的经验。我已经搜索过,但没有找到我的问题的答案,那就是......

由“add_action”创建的钩子是否“添加”到该特定钩子调用的操作列表中,或者它们是否覆盖了该操作的任何现有钩子?

例如,如果我woocommerce_thankyou使用以下方法添加挂钩:

add_action( 'woocommerce_thankyou', 'order_created_get_skus',#);

问题:这是否覆盖了任何其他钩子,woocommerce_thankyou或者除了为 设置的任何其他钩子之外,它还会被调用woocommerce_thankyou吗?

4

1 回答 1

2

钩子函数永远不会覆盖使用相同操作或过滤钩子的其他钩子函数

它们被添加到一种“挂钩队列”中,执行顺序基于优先级规则:

  • 如果指定了优先级,它们将首先按挂钩优先级和声明优先级在队列中排序。
  • 如果没有指定优先级,则默认优先级为 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>';
}

正如您所注意到的,有两种钩子,它们是过滤器钩子和动作钩子。

  1. 动作挂钩:

    • 动作钩子执行点 (触发器):withdo_action()
    • 将函数附加到动作钩子 (触发):with add_action():函数被执行并且可以有可选参数。
  2. 过滤钩:

    • 过滤钩子执行点 (触发器):withapply_filters()
    • 将函数附加到过滤器挂钩 (过滤/触发):使用add_filter():强制参数(变量)被过滤并从“挂钩”函数返回

钩子和它们的钩子函数可以位于任何位置,例如在您的活动子主题 (或活动主题)的 function.php 文件中,也可以在任何插件php 文件中。


有关的:

于 2018-10-11T19:54:24.427 回答