You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WooCommerce单品页展示指定产品属性并向现有代码新增更多属性

WooCommerce单品详情页多属性展示修改方法

你当前使用的单属性展示代码只需调整属性遍历逻辑即可支持多属性输出,具体修改方案如下:

完整修改后代码

将你原来的代码替换为以下代码,可根据需求自行增减要展示的属性:

add_action( 'woocommerce_single_product_summary', 'custom_multiple_attributes_display', 25 );
function custom_multiple_attributes_display() {
    global $product;

    // 此处填写你需要展示的所有产品属性slug,系统创建的属性默认前缀为pa_
    $display_attributes = [
        'pa_color', // 颜色属性示例
        'pa_size', // 尺寸属性示例
        'pa_brand' // 品牌属性示例
    ];

    $html_output = '';
    foreach ( $display_attributes as $attr_slug ) {
        $attr_values = wc_get_product_terms( $product->get_id(), $attr_slug, [ 'fields' => 'names' ] );
        // 若当前产品无对应属性则跳过输出
        if ( empty( $attr_values ) ) continue;

        $html_output .= sprintf(
            '<div class="custom-attribute %s"><strong>%s:</strong>%s</div>',
            esc_attr( $attr_slug ),
            wc_attribute_label( $attr_slug ),
            implode( '、', $attr_values )
        );
    }

    if ( ! empty( $html_output ) ) {
        echo '<div class="custom-attributes-group">' . $html_output . '</div>';
    }
}

配置注意事项

  • 产品属性slug获取路径:登录WordPress后台,进入「产品」-「属性」,点击对应属性的编辑按钮,页面URL中的taxonomy参数值即为属性slug,系统默认生成的全局属性都带有pa_前缀
  • 若需要调整属性展示位置,可修改add_action的第三个优先级参数:数值越小展示位置越靠前,默认25对应展示位置为产品价格下方、加购按钮上方;设置为30则会移到加购按钮下方
  • 你可以通过CSS类名custom-attributes-group自定义整体属性模块样式,也可以通过每个属性自带的slug类名单独设置单属性样式

内容的提问来源于stack exchange,提问作者dan44

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 01:45:00