Woocommerce Subscription get id from order id with API

Viewed 710

Is it possible to get the Subscription id from the Woocommerce order id with the API of WooCommerce? I'm using PHP and with this I can get all the order data, but not subscription id:

$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => "https://www.example.com/wp-json/wc/v3/orders/".$orderId,
    CURLOPT_USERPWD => 'code:code',
    CURLOPT_HTTPHEADER => array(
         "accept: application/json"
    )
]);
$woocommerceOrder = curl_exec($curl);
2 Answers
add_filter( 'woocommerce_api_order_response', 'add_woo_field_order_api_response', 20, 4 );

function add_woo_field_order_api_response( $order_data, $order, $fields, $server ) {

    // Get the subscription id
    $subscriptions_ids  = wcs_get_subscriptions_for_order( $order->get_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
    $order_data[ 'subscription_id' ] = $subscription_id;
    return $order_data;
}

Add this code snippet in your server active theme function.php. Then the order API response will contain the subscription_id

I've solved with this code in my functions.php file in Wordpress:

function prefix_wc_rest_prepare_order_object($response, $object, $request){
    // Get the subscription id
    $subscriptions_ids = wcs_get_subscriptions_for_order($object->get_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 == $object->get_id()){
            break; // Stop the loop
        }
    }
    $response->data['subscription_id'] = $subscription_id;
    return $response;
}
add_filter('woocommerce_rest_prepare_shop_order_object', 'prefix_wc_rest_prepare_order_object', 10, 3);

Thanks to mujuonly for the reference and for the initial snippet.

Related