Search code examples
phpwordpresswoocommerceuseridwoocommerce-subscriptions

How to get the user ID from a WC_Subscription instance Object


I have two functions I need help with that I hope can handle my subscription tasks. The code comments (// ...) is what I'm trying to figure out. If you have other feedback, I'm open to them as well.

This one for completed initial subscription payments and subscription renewals.

function payment_made($subscription){
    // How do I get the User ID from subscription? (Definitely need this)
}
add_action("woocommerce_subscription_payment_complete", "payment_made");

And this one for when a status is changed, so I can handle manual and system changes either manual overrides or failed/pending/active/whatever status based of payments or switches.

function status_update($subscription, $old_status, $new_status){
    // How do I get the User ID from subscription (Definitely need this)
}
add_action("woocommerce_subscription_status_updated", "status_updated");

Solution

  • To get the user id from the WC_Subscription Object, you will use get_user_id() method just as you can do with a WC_Order Object:

    $user_id = $subscription->get_user_id();
    

    Tested and works.

    Related: