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 );

Can you please let me know how to modify it


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.

  • Thanks, and how do I then display the values (separated by space)? – user3767576 Nov 2 '16 at 14:06
  • I've not understood what are you pointing at by "separated by spaces"!! And if you think this answer helped you please accept it. – CodeMascot Nov 2 '16 at 14:36
  • It did help, thank you. I am simply having trouble displaying the values in my template correctly. Can you advise how to display them? – user3767576 Nov 2 '16 at 14:39
  • Can you provide any visible link or picture how you wanna show them? @user3767576 – CodeMascot Nov 2 '16 at 14:41
  • 1
    The code that worked for me is ` $size = $product->get_attribute( 'pa_size' ); global $product; $size = array_values( wc_get_product_terms( $product->id, 'pa_size', array( 'fields' => 'names' ) ) ); $prodsizes=implode(", ",$size); echo $prodsizes;` – user3767576 Nov 2 '16 at 20:01
$product = wc_get_product();
echo $product->get_attribute( 'Size' );

protected by Community Oct 28 '18 at 11:33

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.