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

如何在WooCommerce单品页元数据区隐藏指定产品分类?

解决WooCommerce单品页隐藏指定分类的需求

我需要在WooCommerce单品页的产品元数据区域隐藏特定分类(preorder、fitting)的显示及其链接,但不能取消产品和这些分类的关联——因为这些分类要给YITH等插件提供功能逻辑:带preorder的产品用YITH收定金,带fitting的产品会显示适配服务复选框。

当前单品页分类的HTML输出结构如下:

<div class="product_meta">
    <span class="sku_wrapper">SKU: <span class="sku">...</span></span>
    <span class="posted_in">
            Categories: 
            <a href="URL" rel="tag">Fitting</a>
            , 
            <a href="URL" rel="tag">Category 1</a>
            , 
            <a href="URL" rel="tag">Category 2</a>
            , 
            <a href="URL" rel="tag">Preorder</a>            
    </span>
</div>

PHP方案(推荐)

直接通过WooCommerce钩子从源头过滤分类输出,避免前端多余处理,同时保留产品与分类的关联。

将以下代码添加到主题的functions.php文件或自定义插件中:

add_filter( 'woocommerce_product_get_categories', 'hide_specific_product_categories', 10, 2 );
function hide_specific_product_categories( $categories, $product ) {
    // 定义需要隐藏的分类slug
    $hidden_cats = array( 'preorder', 'fitting' );
    
    $filtered_cats = array();
    foreach( $categories as $category ) {
        if( !in_array( $category->slug, $hidden_cats ) ) {
            $filtered_cats[] = $category;
        }
    }
    
    if( !empty( $filtered_cats ) ) {
        $links = array();
        foreach( $filtered_cats as $category ) {
            $links[] = '<a href="' . esc_url( get_term_link( $category ) ) . '" rel="tag">' . esc_html( $category->name ) . '</a>';
        }
        return implode( ', ', $links );
    } else {
        return '';
    }
}

代码逻辑:

  • 通过woocommerce_product_get_categories钩子拦截分类输出
  • 过滤掉slug为preorder和fitting的分类
  • 重新生成无多余逗号的分类链接字符串

jQuery修复方案(针对前端多余逗号问题)

若无法使用PHP方案,可修复前端JS代码,处理移除分类后残留的多余逗号:

将以下代码添加到主题自定义JS区域或通过wp_enqueue_script加载:

jQuery(document).ready(function($) {
    // 移除指定分类链接
    $('.product_meta .posted_in a').each(function() {
        var catName = $(this).text().toLowerCase();
        if( catName === 'preorder' || catName === 'fitting' ) {
            $(this).remove();
        }
    });
    
    // 清理多余逗号与空格
    var postedInContent = $('.product_meta .posted_in').html();
    // 替换连续的逗号空格组合为单个", "
    postedInContent = postedInContent.replace(/(\s*,\s*)+/g, ', ');
    // 移除开头可能出现的"Categories: , "中的逗号
    postedInContent = postedInContent.replace(/Categories:\s*,/, 'Categories:');
    // 移除结尾残留的逗号
    postedInContent = postedInContent.replace(/,\s*$/, '');
    $('.product_meta .posted_in').html(postedInContent);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 10:32:39