How to get the post ID associated with a Woocommerce Subscription

I am desperately trying to programmatically get the post ID associated with a WooCommerce Subscription object. I am starting from the user id, and trying to request the database using the get_posts function. A call using the get_users_subscriptions works but the objects returned do not include their ID, only the associated order_id or product_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'
) );

The get_post request is sadly returning an empty array. Do you see something wrong in my request ?

Read More

Thanks in advance,

Related posts

Leave a Reply

2 comments

  1. I did not find an easy solution so I went with a SQL request based on the order_id contained in the subscription object I get using the call of:

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

    The $wpdb call looks like the following:

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

    If it helps someone, you’re welcome !

  2. I’ve achieved the same thing with the following code, if you are using the wp rest APIs, it will also add a property to the response:

    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,
        ]);
      }
    );