6

I'm trying to get the subscription id from the action hook woocommerce_order_status_changed.

It gives me the order id which is changed with every switch the customer makes.

For example: If the subscription id is 10, the original order id is 9.

Now every switch the customer made generates a new order id, which the action above gives you. At this point I have the $customer_id, $order_id, and the original post id which is 9,

How I can get the subscription id of the current order?

mujuonly
  • 11,370
  • 5
  • 45
  • 75
Shlomi
  • 337
  • 1
  • 6
  • 19

1 Answers1

16

You can use dedicated function wcs_get_subscriptions_for_order() which will retrieve $subscription IDs.

So this could be your code:

add_action('woocommerce_order_status_changed', 'action_order_status_changed');
function action_order_status_changed( $order_id ){
    $subscriptions_ids = wcs_get_subscriptions_for_order( $order_id, array( 'order_type' => 'any' ) );
    // We get all related subscriptions for this order
    foreach( $subscriptions_ids as $subscription_id => $subscription_obj )
        if($subscription_obj->order->id == $order_id) break; // Stop the loop

    // The subscription ID: $subscription_id 
    // The An instance of the Subscription object: $subscription_obj 
    // ...
}
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • 7
    A note for anyone reading this: I had to set the params for the function as `wcs_get_subscriptions_for_order( $order_id, array( 'order_type' => 'any' ) )` to get this to work. Without the second parameter it was not working for me ( see function `add_subscriptions_to_view_order_templates()` in class-wc-subscriptions-order.php file in the woocommerce-subscriptions plugin which does the same thing). I'm using WC 3.3.5 and Wordpress 4.9.4 – Sarah May 03 '18 at 09:59
  • @Sarah Thanks for your note… – LoicTheAztec May 03 '18 at 11:03
  • @Sarah thanks for your note, it really help full. thanks a lot :) – dev_ramiz_1707 Mar 04 '21 at 15:12