我想在“产品详细信息”页面上显示一组特定的产品属性。像这样:
直到现在,我只找到一个代码来显示产品的每个属性:
global $product;
$attribute = $product->get_attributes();
$attribute_arr = array();
if( count($attribute) > 0 ){
foreach ($attribute as $key => $value) {
$attribute_arr[] = $key;
}
}
问题是,我不想显示所有这些。仅特定的一组属性。 也许我可以使用数组定义要显示的属性。像这样:
array('pa_color', 'pa_size')
我还有一个工作代码来显示特定属性:
<?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; ?>
有没有办法将这两个代码结合起来? 以及如何显示属性的标签(例如颜色)?
答案 0 :(得分:2)
您可以改为使用WordPress wp_get_post_terms()
功能,如下所示:
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>';
}
}
经过测试可以正常工作。