如何使用 WooCommerce 会员挂钩

How to use WooCommerce Membership hook

我正在一个使用 WooCommerce 会员资格的网站上工作。

我正在使用一个名为 wc_memberships_user_membership_saved 的挂钩,我想要的是显示我的订单摘要。

我阅读了这份文档:https://docs.woocommerce.com/document/woocommerce-memberships-admin-hook-reference/#wc_memberships_user_membership_created 了解如何使用此挂钩。

我想测试这个钩子,所以这就是我在 functions.php

中所做的
function gu_memberships_user_membership_saved($user_id,$user_membership_id,$is_update) {
    
    $to = 'mail@test.com';
    $subject = 'The subject';
    $body = '<pre>' . print_r($is_update,true) . '</pre>';
    $headers = array('Content-Type: text/html; charset=UTF-8');
    
    wp_mail( $to, $subject, $body, $headers );
  
}
add_action( 'wc_memberships_user_membership_saved', 'gu_memberships_user_membership_saved' );

我应该收到一个布尔值:true 或 false。但我收到的是 WooCommerce 会员阵列产品。

问题是否出在参数上?

你可以通过下面的方式使用它,使用$body变量,你可以打印参数来查看它包含的内容

  • @type int|string $user_id user ID for the membership
  • @type int|string $user_membership_id post ID for the new user membership
  • @type bool $is_update true if the membership is being updated, false if new
/**
 * Fires after a user has been granted membership access
 *
 * This hook is similar to wc_memberships_user_membership_created
 * but will also fire when a membership is manually created in admin
 *
 * @since 1.3.8
 * @param WC_Memberships_Membership_Plan $membership_plan The plan that user was granted access to
 * @param array $args
 */
function action_wc_memberships_user_membership_saved( $user_id, $user_membership_id, $is_update = 0 ) {

    $to = 'mail@test.com';
    $subject = 'The subject';
    $body = '<pre>', print_r( $user_membership_id, 1 ), '</pre>';
    $headers = array('Content-Type: text/html; charset=UTF-8');

    wp_mail( $to, $subject, $body, $headers );

}
add_action( 'wc_memberships_user_membership_saved', 'action_wc_memberships_user_membership_saved', 10, 3 );

函数声明应该是:

function gu_memberships_user_membership_saved($plan, $args) {

然后 $args 将包含您引用的三个变量的数组,例如 $args['user_id'].