2016-06-08 54 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, 
    ]); 
    } 
);