Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the user ID in WooCommerce Subscriptions

I am using WooCommerce Subscriptions plugin and I am trying to get the customer or userid of a given wc_subscription.

Here is the code I have been using but fails:

add_action( 'woocommerce_scheduled_subscription_trial_end', 'registration_trial_expired', 100 );
function registration_trial_expired( $wc_subscription ) {
    mail("[email protected]", "Expired", "Someone's order has expired");
    $userid = $wc_subscription->customer_user;
    mail("[email protected]", "Expired", "Someone's order has expired with customer".$userid);
...
}

I thought $wc_subscription->customer_user will have the userid but it is empty. In fact stops the code from continuing.

How can I get the user ID with $wc_subscription?

like image 717
user3072613 Avatar asked Mar 10 '23 11:03

user3072613


1 Answers

As class WC_Subscription methods are inherited from WC_Abstract_Order and WC_Order classes, you can use get_user_id() method this way:

$userid = $wc_subscription->get_user_id();

This code is tested and works with WC_Subscription instance object

So your code will be:

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

Update (on OP's comment)

As the argument $wc_subscription was the subscription ID (and not the Subscription object).

So I have changed the code to:

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 = '[email protected]';

    // 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 );

    // ...
}
like image 162
LoicTheAztec Avatar answered Mar 30 '23 03:03

LoicTheAztec