Cray
Cray

Reputation: 5483

WooCommerce: Get name and variation from a Subscription order

I want to display the name of the subscription product in the overview of my active subscriptions. At the moment, the page shows only the subscription order number with the function $subscription->get_order_number()

I printed the array behind $subscription but it seems that the array has no information about the subscription product or the ordered variation.

Is there a way to display the name and the variation of the ordered subscription product?

Displaying the order number only, is not very helpful for the user.

Upvotes: 3

Views: 6015

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253901

A Subscription (just as WC_Order objects) can contain one or more products as line items. So that's why you can see this data.

So Just as WooCommerce orders you need to iterate through the Subscription items to get the product name:

// Set here your subscription ID (if needed)
$subscription_id = 319;

// Get the WC_Subscription object (if needed)
$subscription = wc_get_order($subscription_id); // Or: new WC_Subscription($subscription_id); 

// Iterating through subscription items
foreach( $subscription->get_items() as $item_id => $product_subscription ){
    // Get the name
    $product_name = $product_subscription->get_name();
}

This code is tested and works

Subscription products are an extension of WooCommerce products. So all methods available for WC_Product are usable…


Related official developer documentation:

Upvotes: 9

Related Questions