I am trying to display a single attribute (‘size’) value on shop page. I used the following code to show all values, tried to adapt to to show a single attribute, but with no success…

Can you please help me adapt the code to only display values of the attribute ‘size’?

// Get the attributes
$attributes = $product->get_attributes();
// Start the loop
foreach ( $attributes as $attribute ) : 
    // Check and output, adopted from /templates/single-product/product-attributes.php
    if ( $attribute['is_taxonomy'] ) {
        $values = wc_get_product_terms( $product->id, $attribute['name'], array( 'fields' => 'names' ) );
        echo apply_filters( 'woocommerce_attribute', wpautop( wptexturize( implode( ', ', $values ) ) ), $attribute, $values );
    } else {
        // Convert pipes to commas and display values
        $values = array_map( 'trim', explode( WC_DELIMITER, $attribute['value'] ) );
        echo apply_filters( 'woocommerce_attribute', wpautop( wptexturize( implode( ', ', $values ) ) ), $attribute, $values );
    }
endforeach;

Can you please let me know how to modify it

2 s
2

Just use global $product then use get_attribute() method of that product object, like below-

$size = $product->get_attribute( 'pa_size' );

And you can also get that by below code-

global $product;
$size = array_shift( wc_get_product_terms( $product->id, 'pa_size', array( 'fields' => 'names' ) ) );

Rememeber you need to use must the global $product.

Leave a Reply

Your email address will not be published. Required fields are marked *