WooCommerce如何在single-product页输出全部product_attributes的名称及选项
解决方法
你当前代码的问题是直接以数组形式读取WC_Product_Attribute对象的属性,拿到的都是原始slug值,没有调用WooCommerce内置的格式化方法获取可读内容。
你可以使用以下代码替换原有逻辑,就能输出属性的可读名称和对应的可选值:
<?php global $product; // 获取产品所有属性 $attributes = $product->get_attributes(); foreach ( $attributes as $attribute ) { // 跳过未设置为前台可见的属性,不需要可以删除该行 if ( ! $attribute->get_visible() ) continue; // 获取属性的可读名称(非slug) $attribute_name = $attribute->get_name(); // 获取属性的可选值数组,自动处理全局属性的术语名称转义 $attribute_values = $attribute->get_options(); // 输出结构可根据前端需求自行调整 echo '<div class="product-attribute-item">'; echo '<span class="attribute-name">' . esc_html( $attribute_name ) . ':</span>'; echo '<span class="attribute-values">' . esc_html( implode( '、', $attribute_values ) ) . '</span>'; echo '</div>'; } ?>
补充说明
- 如果你需要输出变体选项的可选值而非普通属性,可以额外调用
$product->get_available_variations()获取变体数据做对应处理 - 输出自带
esc_html()安全转义,符合WordPress编码规范
内容的提问来源于stack exchange,提问作者public9nf
相关产品推荐
相关产品推荐

