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

如何让WordPress/WooCommerce简单产品页面显示属性(同可变产品样式)

解决方案:让WooCommerce简单产品复用可变产品的属性展示样式

直接通过修改主题的functions.php文件添加以下代码,即可让简单产品在对应位置展示和可变产品风格一致的属性,无需创建变体或修改产品类型。

方法一:复用WooCommerce内置模板

这段代码直接调用可变产品的属性模板来渲染简单产品的可见属性,样式会和你当前主题的可变产品属性保持一致:

// 在简单产品页面插入可变产品风格的属性展示
add_action('woocommerce_single_product_summary', 'simple_product_show_variation_style_attributes', 25);
function simple_product_show_variation_style_attributes() {
    global $product;
    
    // 仅对简单产品生效
    if ( ! $product->is_type('simple') ) return;
    
    // 获取产品设置为"在产品页面可见"的属性
    $attributes = $product->get_attributes();
    $visible_attributes = array_filter($attributes, function($attr) {
        return $attr->get_visible();
    });
    
    // 无可见属性时直接返回
    if ( empty($visible_attributes) ) return;
    
    // 加载可变产品的属性模板
    wc_get_template(
        'single-product/add-to-cart/variation.php',
        array(
            'available_variations' => array(),
            'attributes' => $visible_attributes,
            'selected_attributes' => array(),
            'product' => $product
        )
    );
}

方法二:自定义属性渲染结构

如果内置模板不符合需求,可以用这段代码手动生成和可变产品一致的HTML结构,方便自定义调整:

// 自定义渲染简单产品属性,模拟可变产品样式
add_action('woocommerce_single_product_summary', 'simple_product_custom_variation_style_attributes', 25);
function simple_product_custom_variation_style_attributes() {
    global $product;
    
    if ( ! $product->is_type('simple') ) return;
    
    $attributes = $product->get_attributes();
    $visible_attributes = array_filter($attributes, function($attr) {
        return $attr->get_visible();
    });
    
    if ( empty($visible_attributes) ) return;
    
    // 输出可变产品风格的属性HTML结构
    echo '<div class="variations">';
    echo '<table class="variations" cellspacing="0">';
    echo '<tbody>';
    
    foreach ( $visible_attributes as $attribute ) {
        $attr_label = wc_attribute_label($attribute->get_name());
        $attr_value = $product->get_attribute($attribute->get_name());
        
        echo '<tr>';
        echo '<td class="label"><label for="' . esc_attr($attribute->get_name()) . '">' . esc_html($attr_label) . '</label></td>';
        echo '<td class="value"><span class="attribute-value">' . esc_html($attr_value) . '</span></td>';
        echo '</tr>';
    }
    
    echo '</tbody>';
    echo '</table>';
    echo '</div>';
}

使用步骤

  1. 把上述任意一段代码添加到你当前主题的functions.php文件末尾(建议使用子主题,避免主题更新丢失修改)
  2. 编辑你的简单产品,在「产品数据」→「属性」中添加需要展示的属性(比如「容积」「实际重量」)
  3. 勾选属性的「在产品页面上可见」选项,更新产品

完成后,简单产品页面就会在价格下方、加入购物车按钮上方(和可变产品属性位置一致)展示你设置的属性,样式和可变产品保持统一,你可以根据需要自行调整CSS样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 08:47:29