在WoooCommerce订阅中获取用户ID

时间:2017-03-30 04:14:30

标签: php wordpress woocommerce subscriptions woocommerce-subscriptions

我正在使用WoooCommerce Subscriptions插件,我正在尝试获取给定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,但它是空的。实际上会阻止代码继续。

如何使用$wc_subscription获取用户ID?

由于

3 个答案:

答案 0 :(得分:1)

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

wp_get_current_user();

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

派生
$userdata = WP_User::get_data_by( $field, $value );

答案 1 :(得分:1)

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;
    }

答案 2 :(得分:0)

  

由于班级WC_Subscription methods是继承自 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 );

    // ...
}