Wesley
Wesley

Reputation: 205

Getting product variations from WC_Product_Variation

I have a WooCommerce webshop, where T-Shirts are being sold. When a person looks at the cart, I'd like to give them the option to change sized on a T-Shirt. Currently, the dropdown menu i made looks like this:

<?php
    if ( $item->is_type( 'variation' ) ){
?>
<select name="" class="product-size">
<?php
    foreach ( $item->get_available_variations() as $variation ):
?>
        <option value="">test</option>
<?php
    endforeach;
?>
</select>
<?php
   }
? >

However, this gives me the following error:

Fatal error: Uncaught Error: Call to undefined method WC_Product_Variation::get_available_variations()

So then it hit me; my $item variable, is already a variation. Is there a way to get the other variations for the same product?

Thanks

Upvotes: 5

Views: 16595

Answers (2)

MegaSpaceHamlet
MegaSpaceHamlet

Reputation: 371

The type name you should be checking for is 'variable', not 'variation':

if ($product->is_type( 'variable' ) {
    // do code 
}

Here's the source code from WooCommerce that shows the available product types:

/**
 * Get product types.
 *
 * @since 2.2
 * @return array
 */
function wc_get_product_types() {
    return (array) apply_filters(
        'product_type_selector',
        array(
            'simple'   => __( 'Simple product', 'woocommerce' ),
            'grouped'  => __( 'Grouped product', 'woocommerce' ),
            'external' => __( 'External/Affiliate product', 'woocommerce' ),
            'variable' => __( 'Variable product', 'woocommerce' ),
        )
    );
}

Other StackOverflow answers that deal with the issue at hand:

Checking for Product Variations

Subscription Variations

What's important across the board is to first check the product type using the $product->is_type('type') method first. This ensures that the function won't be called on any object that it's not fit for. In order for the conditional to work properly, you need to checking for the appropriate values. Once that's done, the function should work properly.

Upvotes: 1

Vidish Purohit
Vidish Purohit

Reputation: 1078

If you check type of your object, it is of class WC_Order_Item_Product. You can use this

$variationId = $item->get_variation_id();

$variableProduct = new WC_Product_Variable($variationId)

$allVariations = $variableProduct->get_available_variations();

====================================

Oh I see. You can try this.

$parentData = $item->get_parent_id();
$variableProduct = new WC_Product_Variable($parentData)
$allVariations = $variableProduct->get_available_variations();

Upvotes: 2

Related Questions