Reputation: 117
In Woocommerce, I have added a hooked function which displays the product attribute for variation assigned to a variable product on the Woocommerce archive pages:
add_action( 'woocommerce_after_shop_loop_item', 'stock_variations_loop' );
function stock_variations_loop(){
global $product;
if ( $product->get_type() == 'variable' ) {
foreach ($product->get_available_variations() as $key) {
$attr_string = '';
foreach ( $key['attributes'] as $attr_name => $attr_value) {
$attr_string[] = $attr_value;
}
if ( $key['max_qty'] > 0 ) {
echo '<div class="sizeVariantCat">' . implode(', ', $attr_string).'</div>';
}
}
}
}
It is working fine, but some of the data is messy… I only want to display 'Size' product attribute for variation values, not all the products that have a "size" attribute.
Upvotes: 1
Views: 2482
Reputation: 253919
If you want to target the product attribute for variation "size" to get the corresponding values from the product variations set for the variable product, try the following:
add_action( 'woocommerce_after_shop_loop_item', 'display_attribute_size_for_variations' );
function display_attribute_size_for_variations(){
global $product;
// HERE the taxonomy for the targeted product attribute
$taxonomy = 'pa_size';
if ( $product->get_type() == 'variable' ) {
$output = array();
foreach ($product->get_available_variations() as $values) {
foreach ( $values['attributes'] as $attr_variation => $term_slug ) {
// Targetting "Size" attribute only
if( $attr_variation === 'attribute_' . $taxonomy ){
// Add the size attribute term name value to the array (avoiding repetitions)
$output[$term_slug] = get_term_by( 'slug', $term_slug, $taxonomy )->name;
}
}
}
if ( sizeof($output) > 0 ) {
echo '<div class="'.$taxonomy.'-variations-terms">' . implode( ', ', $output ).'</div>';
}
}
}
Code goes in function.php file of your active child theme (or theme). tested and works.
Upvotes: 6