php - WooCommerce: Get multiple specific product attributes with attribute label

I want to display a set of specific product attributes on the product details page. Like this:
- Colors: blue, red
- Sizes: M, L, XL
Until now I only found a code to show every attribute of a product:
global $product;
$attribute = $product->get_attributes();
$attribute_arr = array();
if( count($attribute) > 0 ){
foreach ($attribute as $key => $value) {
$attribute_arr[] = $key;
}
}
The problem is, that I dont want to show all of them. Only a specific set of attributes. Maybe I could use a array to define the attributes I want to show. Something like:
array('pa_color', 'pa_size')
I also have a working code to show a specific attribute:
<?php
global $product;
$pa_colors = wc_get_product_terms( $product->get_id(), 'pa_color', array( 'fields' => 'all', 'orderby' => 'menu_order' ) );
if( $pa_colors ) : ?>
<ul>
<?php foreach ( $pa_colors as $pa_color ) : ?>
<li>
<?php echo $pa_color->name; ?>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
Is there a way to combine these two codes? And how could I show the label (e.g. color) for the attributes?
Answer
Solution:
You could use instead the WordPresswp_get_post_terms()
function as follow:
global $product;
$attribute_taxonomies = array('pa_colors', 'pa_sizes'); // Defined product attribute taxonomies
// Loop through your defined product attributes taxonomies:
foreach ( $attribute_taxonomies as $attribute ) {
$term_names = wp_get_post_terms( get_the_id(), $attribute, ['fields' => 'names'] );
if( ! empty( $term_names ) ) {
echo '<p><strong>' . wc_attribute_label($attribute) . ':</strong> ' . implode(', ', $term_names) . '</p>';
}
}
Tested and works.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: git was not found in your path, skipping source download
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.