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

如何在Woocommerce单品页面隐藏指定产品分类?

WooCommerce单品页隐藏指定分类解决方案

原代码不生效的核心原因

  • 仅定义了自定义函数,没有挂载到WooCommerce单品页的对应输出钩子上,函数从未被触发执行
  • 没有移除WooCommerce默认的分类输出逻辑,就算自定义函数生效也会出现重复显示的问题
  • $result变量未初始化,PHP运行时会抛出notice警告,如果所有分类都被过滤,substr操作还会出现异常

最优实现方案

直接通过钩子替换默认的分类输出逻辑,无需修改主题模板文件,代码轻量且不影响分类本身的正常访问、收录:

  1. 先获取需要隐藏的分类ID:进入后台「产品-分类」,点击对应分类编辑,URL参数里的tag_ID值就是分类ID
  2. 将以下代码添加到当前主题的functions.php文件中,或通过代码片段插件插入:
// 移除WooCommerce默认的单品元信息输出
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_meta', 40 );
// 挂载自定义的单品元信息输出
add_action( 'woocommerce_single_product_summary', 'custom_hide_specific_product_cats', 40 );

function custom_hide_specific_product_cats() {
    global $product;
    // 在这里填写需要隐藏的分类ID,多个用英文逗号分隔
    $exclude_cat_ids = array(2, 4);
    
    $categories = wc_get_product_category_list( $product->get_id(), ', ', '', '' );
    // 过滤排除指定分类
    foreach ($exclude_cat_ids as $cat_id) {
        $cat = get_term( $cat_id, 'product_cat' );
        if ($cat && !is_wp_error($cat)) {
            $cat_link = get_term_link( $cat );
            $cat_html = '<a href="' . esc_url( $cat_link ) . '" rel="tag">' . esc_html( $cat->name ) . '</a>';
            $categories = str_replace($cat_html . ', ', '', $categories);
            $categories = str_replace(', ' . $cat_html, '', $categories);
            $categories = str_replace($cat_html, '', $categories);
        }
    }
    $categories = trim($categories, ', ');
    
    // 输出分类
    if ( $categories ) {
        echo '<span class="posted_in">' . _n( 'Category:', 'Categories:', count( $product->get_category_ids() ), 'woocommerce' ) . ' ' . $categories . '</span>';
    }
    
    // 保留默认的标签、SKU等其他元信息输出
    if ( wc_product_sku_enabled() && ( $product->get_sku() || $product->is_type( 'variable' ) ) ) {
        echo '<span class="sku_wrapper">' . esc_html__( 'SKU:', 'woocommerce' ) . ' <span class="sku">' . ( $sku = $product->get_sku() ) ? $sku : esc_html__( 'N/A', 'woocommerce' ) . '</span></span>';
    }
    echo wc_get_product_tag_list( $product->get_id(), ', ', '<span class="tagged_as">' . _n( 'Tag:', 'Tags:', count( $product->get_tag_ids() ), 'woocommerce' ) . ' ', '</span>' );
}

注意事项

  • 若使用的主题自定义过单品页结构,上述钩子的优先级(代码里的40)可能和默认不同,不生效时可调整优先级数值匹配主题设置
  • 该方案仅隐藏单品页的分类显示,分类归档页保持正常访问,完全不影响搜索引擎收录

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 16:06:03