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

WooCommerce 导航到子分类页面后如何隐藏对应子分类展示文本?

方案1:修改PHP逻辑(推荐)

直接在原有函数中增加分类层级判断,仅顶级分类输出目标内容,修改后的完整代码如下:

add_action('woocommerce_after_subcategory_title', 'woocommerce_subcats_from_parentcat_by_ID', 30);

function woocommerce_subcats_from_parentcat_by_ID($category)
{
    $parent_category_ID = $category->term_id;
    // 获取当前分类的父级ID
    $category_parent_id = $category->parent;
    $args = array(
        'hierarchical' => 1,
        'show_option_none' => '',
        'hide_empty' => 0, // 设为0展示空分类,设为1隐藏空分类
        'parent' => $parent_category_ID,
        'taxonomy' => 'product_cat'
    );
    $subcategories = get_categories($args);
    echo '<div class="custom_subcategory_main">';
    // 仅顶级分类(父级ID为0)输出子分类列表模块
    if($category_parent_id == 0) {
        echo '<span class="custom_subcategory_klasy">Dostępne klasy:</span><br>';
        foreach ($subcategories as $subcategory) {
            echo '<span> '.$subcategory->name.'</span>';
        }
        echo '<br>';
    }
    echo '<span class="custom_subcategory_klasy">Poziom:</span><br>';
    echo '<span>Szkoła podstawowa</span>';
    echo '</div>';
}

逻辑说明:通过判断当前渲染的分类父级ID,只有顶级分类才会输出「Dostępne klasy」及对应的子分类列表,子分类页面会自动跳过该部分内容,不影响其他功能。


方案2:CSS隐藏(无需修改原有代码)

如果不想调整PHP代码,可以直接在后台外观-自定义-额外CSS中添加如下代码:

/* 子分类页面隐藏目标内容 */
.tax-product_cat [class*="term-parent"]:not(.term-parent-0) .custom_subcategory_klasy:first-of-type,
.tax-product_cat [class*="term-parent"]:not(.term-parent-0) .custom_subcategory_klasy:first-of-type + br,
.tax-product_cat [class*="term-parent"]:not(.term-parent-0) .custom_subcategory_klasy:first-of-type ~ span:not(.custom_subcategory_klasy) {
    display: none;
}

逻辑说明:WooCommerce会自动给分类页面元素添加对应层级的类名,该CSS会命中所有非顶级分类页面下的目标元素,直接隐藏对应内容。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 08:18:03