如何在WooCommerce商品页显示多个属性?现有代码仅支持单个
如何修改WooCommerce短代码以展示多个商品属性
下面是修改后的代码,支持通过短代码参数指定多个要展示的商品属性,同时保留了原代码的商品ID兼容逻辑:
function get_product_attributes_shortcode( $atts ) { // 解析短代码参数,支持指定商品ID和要展示的属性slug(逗号分隔) $atts = shortcode_atts( array( 'id' => get_the_ID(), 'attributes' => '', // 示例:'styletypes,color,size' ), $atts, 'display-attributes' ); global $product; // 确保$product对象正确 if ( ! is_a( $product, 'WC_Product' ) ) { $product = wc_get_product( $atts['id'] ); } if ( ! is_a( $product, 'WC_Product' ) ) { return ''; // 商品不存在时返回空 } // 如果没有指定属性,默认返回空(也可改为展示所有可见属性,按需调整) if ( empty( $atts['attributes'] ) ) { return ''; } $attributes_list = explode( ',', $atts['attributes'] ); $output = '<div class="product-attributes">'; foreach ( $attributes_list as $attribute_slug ) { $attribute_slug = trim( $attribute_slug ); // 获取属性的友好名称(后台设置的名称) $attribute_label = wc_attribute_label( $attribute_slug ); // 获取属性值 $attribute_value = $product->get_attribute( $attribute_slug ); // 仅当属性有值时才输出 if ( ! empty( $attribute_value ) ) { $output .= '<div class="attribute-item"><strong>' . esc_html( $attribute_label ) . '</strong>: ' . esc_html( $attribute_value ) . '</div>'; } } $output .= '</div>'; return $output; } add_shortcode( 'display-attributes', 'get_product_attributes_shortcode' );
使用说明:
- 在商品页面或文章中添加短代码,指定要展示的属性slug(多个用逗号分隔):
[display-attributes attributes="styletypes,color,size"] - 若需要指定特定商品的属性,可加上
id参数:[display-attributes id="123" attributes="styletypes,color"] - 代码中加入了
esc_html()来防范XSS安全风险,同时仅输出有值的属性,避免空内容占位。
样式自定义(可选):
可以通过CSS调整展示样式,比如:
.product-attributes { margin: 15px 0; padding: 10px; border: 1px solid #eee; border-radius: 4px; } .attribute-item { margin-bottom: 8px; line-height: 1.5; }
内容的提问来源于stack exchange,提问作者Marco Van
相关产品推荐
相关产品推荐

