更新: 添加了 WooCommerce 版本 3+ 兼容性
从订阅对象中获取订单 ID 非常容易。就像你一样,我将选择来自post 表的所有订阅。'post status' = 'wc-active'
// 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>';
}
您还可以在帖子查询'meta_key'
和'meta_value'
数组行中取消注释以获取一位客户的订阅...此代码经过测试并且有效
这里最重要的是:
$subscription = new WC_Subscription($customer_subscription->ID);
...因为您将获得 WC_Subscription 对象,您可以在其中应用所有 WC_Subscription 方法而不会出错,例如:
$subscription = new WC_Subscription($post_id);
$relared_orders_ids_array = $subscription->get_related_orders();