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
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
Share Improve this question edited Nov 2, 2016 at 3:32 CodeMascot 4,5372 gold badges15 silver badges25 bronze badges asked Nov 1, 2016 at 23:22 nadyawellnadyawell 711 gold badge1 silver badge3 bronze badges2 Answers
Reset to default 11Just 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
.
$product = wc_get_product();
echo $product->get_attribute( 'Size' );