skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    Solved:

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


  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search