Search code examples
phpwordpresswoocommerceauthorwoocommerce-subscriptions

Get Subscription Product author of a Woocommerce subscription


How can I iterate through all current active woo subscriptions and print the user ID of the user who published the product related to each active subscription (PHP)? I think something like this will give just the subscriptions:

$args = array( 'subscriptions_per_page' => -1, 'post_type'   => 'shop_subscription', // WC orders post type
                'post_status' => 'wc-active' );
            $subscriptions = wcs_get_subscriptions( $args );

Solution

  • The following code will query all active subscriptions to get the author Id (that published the product of the active subscription):

    // Get all active subscriptions
    $subscriptions = wcs_get_subscriptions( array(
        'subscriptions_per_page' => -1,
        'subscription_status' => array('active') // Active subscriptions
    ) );
    
    // 1) Loop through quieried active subscriptions
    foreach($subscriptions as $subscription)
    {
        // 2) Loop through subscription items
        foreach( $subscription->get_items() as $item_id => $item ) 
        {
            // Get the subscription product author
            $author_id = get_post_field ('post_author', $item->get_product_id());
            // Display
            echo $author_id . '<br>';
        }
    }
    

    Tested and works.