Home > Net >  WooCommerce PHP API: get all variations - both available and unavailable
WooCommerce PHP API: get all variations - both available and unavailable

Time:01-13

I want to know if it is possible to get all variations from a product - both available variations and unavailable variations. For example if a variation doesn't have a price set, it will be marked as unavailable.

When I call $product->get_available_variations() it only returns the available variations. Any way to get unavailable variations as well?

CodePudding user response:

To get all variations of a product you can make an API call using the wc_get_product() function to get the product object and then use the get_available_variations() method to get the available variations or the get_children() method to get all variations, both available and unavailable.

Here is an example of how this can be done:

<?php
require_once( 'path/to/woocommerce/woocommerce.php' );

$product_id = 1234; // ID of the product

$product = wc_get_product( $product_id );
$variations = $product->get_children();

foreach ( $variations as $variation_id ) {
    $variation = wc_get_product( $variation_id );
    if ( $variation->is_in_stock() && $variation->is_purchasable() ) {
        // Available variation
    } else {
        // Unavailable variation
    }
}

This will retrieve all variations for the product with the specified ID, and loop through each one, checking if it is in stock and purchasable, marking as available or unavailable accordingly.

CodePudding user response:

Solved:

I managed to get all variation ids by calling $product->get_children()

  • Related