Woocommerce 订阅从 API 的订单 ID 获取 ID

Woocommerce Subscription get id from order id with API

是否可以使用 WooCommerce API 从 Woocommerce 订单 ID 获取订阅 ID? 我正在使用 PHP 并且通过此我可以获得所有订单数据,但不是订阅 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);
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;
}

将此代码片段添加到您的服务器活动主题中 function.php。然后订单 API 响应将包含 subscription_id

我已经在 Wordpress 的 functions.php 文件中用这段代码解决了问题:

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

感谢 mujuonly 提供参考和初始片段。