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

如何修改WooCommerce自定义变体表格,仅显示有值的属性列?

修改后的代码实现动态显示有有效值的属性列
add_action( 'woocommerce_after_single_product_summary', 'custom_table_after_single_product' );
function custom_table_after_single_product(){
    global $product;
    if( ! $product->is_type('variable')) return; 

    $available_variations = $product->get_available_variations();
    if( count($available_variations) === 0 ) return;

    // 定义需要检查的属性:键是属性slug,值是表头显示名称
    $attributes_to_check = [
        'pa_colour_range'     => __( 'Colour', 'woocommerce' ),
        'pa_technology'       => __( 'Technology', 'woocommerce' ),
        'pa_posneg'           => __( 'Positive/Negative', 'woocommerce' )
    ];

    // 记录哪些属性存在有效值
    $active_attributes = [];

    // 先遍历所有变体,筛选出有值的属性
    foreach( $available_variations as $variation ){
        $product_variation = wc_get_product($variation['variation_id']);
        
        foreach( $attributes_to_check as $attr_slug => $attr_name ){
            $attr_value = $product_variation->get_attribute($attr_slug);
            // 如果该属性有非空值,标记为需要显示
            if( !empty(trim($attr_value)) ){
                $active_attributes[$attr_slug] = $attr_name;
            }
        }
    }

    // 开始构建表格
    $output = '<table>
        <thead>
            <tr>
                <th>'. __( 'Image', 'woocommerce' ) .'</th>
                <th>'. __( 'SKU', 'woocommerce' ) .'</th>';

    // 添加有有效值的属性表头
    foreach( $active_attributes as $attr_name ){
        $output .= '<th>'. $attr_name .'</th>';
    }

    $output .= '
            </tr>
        </thead>
        <tbody>';

    // 遍历变体生成表格行
    foreach( $available_variations as $variation ){
        $product_variation = wc_get_product($variation['variation_id']);
        
        $output .= '<tr>
            <td>'. $product_variation->get_image('snippets') .'</td>
            <td>'. $product_variation->get_sku() .'</td>';

        // 只输出有有效值的属性列
        foreach( array_keys($active_attributes) as $attr_slug ){
            $output .= '<td>'. $product_variation->get_attribute($attr_slug) .'</td>';
        }

        $output .= '</tr>';
    }

    $output .= '
        </tbody>
    </table>';

    echo $output;
}

关键修改说明

  • 统一管理属性:用$attributes_to_check数组把需要检查的属性slug和对应显示名称整合,后续新增/修改属性只需调整这个数组即可。
  • 提前筛选有效属性:先遍历所有变体,检查每个属性是否有非空有效值,把需要显示的属性存入$active_attributes。
  • 动态生成表头:表头不再固定写死,而是根据$active_attributes动态添加列,确保只显示有内容的属性。
  • 动态输出表格行:表格行的属性列同样只输出$active_attributes里记录的属性,避免出现空列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 08:13:11