skip to Main Content

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


  1. Chosen as BEST ANSWER

    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.


  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search