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