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

如何在WooCommerce的variation.php中显示属性变体描述

在WooCommerce的variation.php中显示属性变体描述

要替换默认的产品变体描述,展示后台Attributes模块下添加的属性变体描述,可按以下步骤操作:

1. 传递属性变体描述到前端数据

在主题(推荐用子主题)的functions.php文件中添加以下代码,把属性变体的描述注入到变体数据中:

add_filter( 'woocommerce_available_variation', 'inject_attribute_term_description', 10, 3 );
function inject_attribute_term_description( $variation_data, $product, $variation ) {
    // 遍历当前变体关联的所有属性
    foreach( $variation->get_variation_attributes() as $taxonomy => $term_slug ) {
        $term = get_term_by( 'slug', $term_slug, $taxonomy );
        if ( $term && ! is_wp_error( $term ) ) {
            // 将属性描述存入变体数据,自定义键名便于前端调用
            $variation_data['attribute_term_desc'] = wpautop( $term->description );
            // 若产品有多个属性,可添加判断指定仅获取某类属性(比如pa_color):
            // if ( $taxonomy === 'pa_color' ) { ... }
            break; // 只取第一个属性的描述,需多属性可移除该行
        }
    }
    return $variation_data;
}

2. 修改variation.php模板

找到主题目录下的woocommerce/single-product/add-to-cart/variation.php文件,替换默认的变体描述代码:

原默认代码(类似):

{{{ data.variation.variation_description }}}

替换为:

{{{ data.variation.attribute_term_desc }}}

如果需要空描述时不显示容器,可改为:

<# if ( data.variation.attribute_term_desc ) { #>
    <div class="variation-attribute-description">
        {{{ data.variation.attribute_term_desc }}}
    </div>
<# } #>

注意事项

  • 务必使用子主题修改文件,避免主题更新时丢失自定义内容;
  • 若需针对特定属性展示描述,在第一步的代码中添加 taxonomy 判定即可精准筛选。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 23:50:07