在Wordpress和Woocommerce中,挂钩及其挂钩函数执行队列

时间:2018-10-11 16:54:25

标签: php wordpress woocommerce hook-woocommerce hook-wordpress

我对Wordpress / WooCommerce和PHP还是陌生的,尽管我在其他Web平台和语言方面也有经验。我已经搜索过,但没有找到我的问题的答案。

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

例如,如果我使用以下方式添加一个woocommerce_thankyou钩子:

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

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

1 个答案:

答案 0 :(得分:0)

  

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

     

它们根据优先级规则以执行顺序添加到“挂钩队列” 中:

     
      
  • 如果指定了优先级,则将首先根据钩子优先级和声明优先级对它们进行排序。
  •   
  • 如果未指定优先级,则它们的默认优先级为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. 动作挂钩:

    • 动作挂钩执行点(触发):带有do_action()
    • 将功能附加到动作挂钩 (已触发):使用add_action():该功能已执行且可以具有可选参数。
  2. 过滤器挂钩:

    • 过滤器挂钩执行点(触发):带有apply_filters()
    • 将函数附加到过滤器挂钩 (过滤/触发):带有add_filter():必填参数(变量)会从“挂钩”函数中过滤并返回
  

钩子及其钩子函数可以位于任何位置,例如您的活动子主题 (或活动主题)的function.php文件以及任何插件 php文件。


相关:

相关问题