4

我正在使用 WooCommerce 订阅插件,并且正在尝试获取给定 wc_subscription 的客户或用户 ID。

这是我一直在使用但失败的代码:

add_action( 'woocommerce_scheduled_subscription_trial_end', 'registration_trial_expired', 100 );
function registration_trial_expired( $wc_subscription ) {
    mail("example@gmail.com", "Expired", "Someone's order has expired");
    $userid = $wc_subscription->customer_user;
    mail("example@gmail.com", "Expired", "Someone's order has expired with customer".$userid);
...
}

我以为$wc_subscription->customer_user会有用户ID,但它是空的。实际上阻​​止了代码继续。

如何获取用户 ID $wc_subscription

4

3 回答 3

4

由于类WC_Subscription 方法WC_Abstract_Order是从和类继承的WC_Order,因此您可以这样使用get_user_id()方法:

$userid = $wc_subscription->get_user_id();

此代码经过测试并与 WC_Subscription 实例对象一起使用

所以你的代码将是:

add_action( 'woocommerce_scheduled_subscription_trial_end', 'registration_trial_expired', 100 );
function registration_trial_expired( $wc_subscription ) {
    mail("example@gmail.com", "Expired", "Someone's order has expired");
    $userid = $wc_subscription->get_user_id(); // <= HERE
    mail("example@gmail.com", "Expired", "Someone's order has expired with customer".$userid);
    // ...
}

更新 (关于 OP 的评论)

因为参数$wc_subscription是订阅 ID (而不是订阅对象)

所以我将代码更改为:

add_action( 'woocommerce_scheduled_subscription_trial_end', 'registration_trial_expired', 100 );
function registration_trial_expired( $subscription_id ) {

    // Get an occurrence of the WC_Subscription object
    $subscription = wcs_get_subscription( $subscription_id );
    
    // Get the user ID (or customer ID)
    $user_id = $subscription->get_user_id();

    // The email adress
    $email = 'example@gmail.com';

    // The theme domain (replace with your theme domain for localisable strings)
    $domain = 'woocommerce';
    
    mail( $email, 'Expired', __("Someone’s order has expired", $domain);
    mail( $email, 'Expired', __("Someone’s order has expired with customer", $domain) . $user_id );

    // ...
}
于 2017-03-30T05:29:19.057 回答
3

WC_Subscription 是 WC_ORDER 的扩展版本,因此您可以使用与 WC_ORDER 相同的调用。

您的代码进行了调整:

 add_action( 'woocommerce_scheduled_subscription_trial_end', 'registration_trial_expired', 100 );
 function registration_trial_expired( $wc_subscription ) 
    {
    $order_billing_email = $wc_subscription->get_billing_email(); 
    $User      = get_user_by( 'email', $order_billing_email );             /
    $FirstName = $User->first_name;
    $LastName  = $User->last_name;
    $UserId    = $User->ID;
    }
于 2019-06-05T20:16:07.583 回答
1

检索当前用户对象 (WP_User)。使用全局变量 $current_user 封装 get_currentuserinfo()。

wp_get_current_user();

但它可能已被弃用,因此您可以从

$userdata = WP_User::get_data_by( $field, $value );
于 2017-03-30T05:23:34.763 回答