Reputation: 363
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
?
Upvotes: 6
Views: 8016
Reputation: 481
WC_Subscription is a expanded version of WC_ORDER, thus you can use the same calls as WC_ORDER.
Your code tweaked:
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;
}
Upvotes: 4
Reputation: 253921
As class WC_Subscription methods are inherited from
WC_Abstract_Order
andWC_Order
classes, you can useget_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 );
// ...
}
Upvotes: 8
Reputation: 745
Retrieve the current user object (WP_User). Wrapper of get_currentuserinfo() using the global variable $current_user.
wp_get_current_user();
But it may be deprecated so You can derived from
$userdata = WP_User::get_data_by( $field, $value );
Upvotes: 1