2016-06-08 80 views
0

我拼命地試圖以編程方式獲取與WooCommerce訂閱對象相關聯的帖子ID。我從用戶標識開始,嘗試使用get_posts函數請求數據庫。使用get_users_subscriptions的呼叫有效,但返回的對象不包括它們的ID,僅包含關聯的order_idproduct_id如何獲得與Woocommerce訂閱相關的帖子ID

$subscriptions = WC_Subscriptions_Manager::get_users_subscriptions(
    $current_user->ID 
); 

$subscription_posts = get_posts(array(
     'orderby'  => 'date', 
     'order'  => 'ASC', 
     'numberposts' => 1, 
     'meta_key' => '_customer_user', 
     'meta_value' => $current_user->ID, 
     'post_type' => 'shop_subscription' 
)); 

get_post請求可悲地返回一個空數組。我的請求中有錯嗎?

由於提前,

回答

1

我沒有找到一個簡單的解決方案,所以我有一個SQL請求,就基於包含在認購對象中的order_id我開始使用的電話:

$subscriptions = WC_Subscriptions_Manager::get_users_subscriptions(
    $current_user->ID 
); 

的$ wpdb調用如下所示:

$subscription_id = $wpdb->get_var(
    "SELECT ID 
     FROM $wpdb->posts 
     WHERE `post_type`='shop_subscription' 
     AND `post_parent`=$first_order->ID 
     ORDER BY `post_date` ASC 
     LIMIT 1;" 
); 

如果有幫助,歡迎您!

0

我已經取得了同樣的事情,用下面的代碼,如果你使用的是WP的REST API,它也將一個屬性添加到響應:

add_action(
    'rest_api_init', 
    function() { 

    // add _subscription_id to wc-order response 
    register_rest_field('shop_order', '_subscription_id', [ 
     'get_callback' => function ($order) { 
     $subscriptionIds = wcs_get_subscriptions_for_order($order['id']); 

     foreach($subscriptionIds as $subscriptionId => $subscription) 
      if($subscription->order->id == $order['id']) break; 

     foreach($order['meta_data'] as $meta) 
      if ($meta->key === '_subscription_renewal') { 
      $metaSubscriptionId = $meta->value; break; 
      } 

     return $subscriptionId ?: (int) $metaSubscriptionId; 
     }, 
     'update_callback' => null, 
     'schema'   => null, 
    ]); 
    } 
);