6

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

9

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
  • 2
    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
-1
$product = wc_get_product();
echo $product->get_attribute( 'Size' );

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