Woocommerce Subscriptions: Get product variations if product is a Subscription Product

1.9k Views Asked by At

In order to return an array of available variations for the current product in WooCommerce, I would use something like this:

 global $product;
 
 $variations = $product->get_available_variations();

I am trying to achieve the same for when a product is added as a variable subscription product and was under the impression that since subscription products are an extension of WooCommerce products shouldn't the same methods work?

Chris

1

There are 1 best solutions below

2
On

As Subscription Variable product extend WooCommerce WC_Product_Variable Class, so they can use mostly all available methods that WooCommerce Variable product can use. But they have also their own methods described in WC_Product_Variable_Subscription Class php file. Their product type is "variable-subscription".

For Product Subscription variation it's similar as they extend WooCommerce WC_Product_Variation Class, so they can use mostly all available methods that WooCommerce Product variation can use. But they have also their own methods described in WC_Product_Subscription_Variation Class php file. Their product type is "subscription_variation".

So your code will be:

global $product;

// Only for Variable subscription product
if ( $product->is_type('variable-subscription') ) {
 
    $available_variations = $product->get_available_variations();
 
    // Loop through available subscription variation products data
    foreach ( $available_variations as $variation_data ) {
        // Output formatted raw data (array)
        echo '<pre>'; print_r( $variation_data ); echo '</pre>';
    }
}

Tested and works