WooCommerce Subscriptions - Get related orders Ids for a specific subscription

荒凉一梦 提交于 2019-12-01 16:12:14

Updated: Added WooCommerce version 3+ Compatibility

It's very easy to get the order ID from subscription object. I am going to select, just like you, all subscriptions where 'post status' = 'wc-active' from post table.

// Get all customers subscriptions
$customer_subscriptions = get_posts( array(
    'numberposts' => -1,
    // 'meta_key'    => '_customer_user',
    // 'meta_value'  => get_current_user_id(), // Or $user_id
    'post_type'   => 'shop_subscription', // WC orders post type
    'post_status' => 'wc-active' // Only orders with status "completed"
) );

// Iterating through each post subscription object
foreach( $customer_subscriptions as $customer_subscription ){
    // The subscription ID
    $subscription_id = $customer_subscription->ID

    // IMPORTANT HERE: Get an instance of the WC_Subscription Object
    $subscription = new WC_Subscription( $subscription_id );
    // Or also you can use
    // wc_get_order( $subscription_id ); 

    // Getting the related Order ID (added WC 3+ comaptibility)
    $order_id = method_exists( $subscription, 'get_parent_id' ) ? $subscription->get_parent_id() : $subscription->order->id;

    // Getting an instance of the related WC_Order Object (added WC 3+ comaptibility)
    $order = method_exists( $subscription, 'get_parent' ) ? $subscription->get_parent() : $subscription->order;

    // Optional (uncomment below): Displaying the WC_Subscription object raw data
    // echo '<pre>';print_r($subscription);echo '</pre>';
}

You can also uncomment in the post query the 'meta_key' and 'meta_value' array lines to get the subscriptions for one customer… This code is tested and works

The most important thing here is:

$subscription = new WC_Subscription($customer_subscription->ID);

…as you will get the WC_Subscription object in which you can apply all WC_Subscription methods without getting errors, with for example:

$subscription = new WC_Subscription($post_id);
$relared_orders_ids_array = $subscription->get_related_orders();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!