You need to enable JavaScript to run this app. 如何修改现有代码实现仅在指定WooCommerce产品分类的单商品页显示自定义文本
优惠活动
大模型
产品
解决方案
定价
更多

如何修改现有代码实现仅在指定WooCommerce产品分类的单商品页显示自定义文本

按指定产品分类显示自定义文本的代码调整方案
  • 实现原理:借助WooCommerce内置的has_term()函数校验当前单商品所属的产品分类,仅匹配到目标分类时才渲染自定义文本模块,全程不影响原有短描述的正常展示
  • 关键注意点:不要将分类判断逻辑放在函数最开头直接返回,否则会造成非目标分类下的商品短描述缺失,破坏原有页面功能
  • 配置说明:仅需要修改代码中的目标分类数组,填入需要展示自定义文本的分类ID、分类别名(slug)即可,支持同时配置多个分类

调整后的完整可用代码如下:

function custom_single_excerpt(){
    global $post, $product;

    $short_description = apply_filters( 'woocommerce_short_description', $post->post_excerpt );

    if ( ! $short_description )
        return;

    // 配置项:替换为需要展示自定义文本的产品分类,支持填分类ID、slug、名称,多个分类用数组形式传入
    $target_categories = array( 'clothing', 15, 'home-decor' );
    // 自定义展示文本
    $custom_text = 'custom text goes in here, custom text goes in here, custom text goes in here, custom text goes in here';

    ?>
    <div class="woocommerce-product-details__short-description">
        <?php echo $short_description // WPCS: XSS ok. ?>
        <?php 
        // 仅当前商品属于指定分类时,才输出自定义文本块
        if ( has_term( $target_categories, 'product_cat', get_the_ID() ) ) : 
        ?>
        <div class="custom-text">
            <?php echo $custom_text; // WPCS: XSS ok. ?>
        </div>
        <?php endif; ?>
    </div>
    <?php
}

实用使用提示

  • has_term()函数的第二个参数必须固定为'product_cat',这是WooCommerce产品分类对应的固定分类法标识,不可随意修改
  • 配置目标分类时优先使用分类ID或slug,避免后续修改分类名称导致判断逻辑失效
  • 如果需要为不同分类配置专属的自定义文本,可在分类判断块内增加分支匹配逻辑,对应输出不同内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.29 21:15:03