Recoil Design
Recoil Design

Reputation: 111

Get for a specific attribute of a variation the corresponding data value

I'm editing the variable-subscription.php file in attempt to display a specific WooCommerce Variable Subscription attribute, along with certain attribute data. Here's my code so far, you can see I'm trying to display the attribute name along with the variation image and description.

<?php

// get all variations
$variations = $product->get_available_variations();
// get shirt values
$shirt_values = get_the_terms( $product_id, 'pa_shirt');
// for each shirt value
foreach ( $shirt_values as $shirt_value ) { ?>

<h1>
    <?php // name
        echo echo $shirt_value->name;
    ?>
</h1>
        
<?php // description
    foreach ( $variations as $variable_array ){
        $variation = new WC_Product_Variation( $variable_array['variation_id'] );
        echo $variation->variation_description;
    }
?>

<?php // image
    foreach ( $variations as $variation ) { ?>
        <img src="<?php echo $variation['image_src']; ?>">
    <?php }
?>
        

Currently, I have 3 shirts for sale (defined in the custom product attributes) and then I have several variations. The problem is this PHP shows ALL possible description/image variations for each shirt, and I only want to show the variations related to each specific shirt attribute.

Upvotes: 3

Views: 2729

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253919

You need to use with the class WC_Product_Variation the method get_variation_attributes() that will returns an array of the attributes and their values for this variation.

So for attribute pa_shirt your code to display the value for a specific variation is going to be:

$variations = $product->get_available_variations();

// Here we use our method to get the array of attribute values for the variation
$variation_attribute = $variation->get_variation_attributes();

// Here is the value for this variation and "pa_shirt" attribute
$variation_attrib_shirt_value = $variation_attribute['attribute_pa_shirt'];

As you can notice the attributes keys slugs in the array have all 'attribute_' in the beginning.

Upvotes: 1

Related Questions