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

WooCommerce归档页仅显示子分类描述,隐藏父分类描述求助

解决WooCommerce子分类页仅显示当前分类描述的问题

问题说明

当前使用以下代码在产品分类页显示描述时,子分类页面会同时展示父分类的描述,需要调整为仅显示当前子分类的描述:

<?php 
 global $post;
$args = array( 'taxonomy' => 'product_cat');
$terms = get_the_terms($category->slug,'product_cat', $args);

    $count = count($terms); 
    if ($count > 0) {

        foreach ($terms as $term) {
            echo '<div class="prod-descr" style="direction:ltl;">';
            echo $term->description;
            echo '</div>';

        }

    }

?>  

解决思路

原代码的问题在于get_the_terms()会返回当前分类的所有父级术语,导致子分类页同时输出父分类描述。我们可以直接获取当前页面的分类对象,而非遍历所有关联术语,或者在循环中判断术语是否为当前页面的分类。

修正后的代码

方法一:直接获取当前分类对象(推荐)

<?php
// 获取当前分类页的分类对象
$current_category = get_queried_object();

// 检查是否为产品分类且存在描述
if ($current_category instanceof WP_Term && $current_category->taxonomy === 'product_cat' && !empty($current_category->description)) {
    echo '<div class="prod-descr" style="direction:ltl;">';
    echo $current_category->description;
    echo '</div>';
}
?>

方法二:在原代码基础上添加判断条件

如果要保留原代码的结构,只需在循环中增加判断,确保只输出当前分类的描述:

<?php 
global $category; // 确保$category变量可用,分类页默认存在该变量
$args = array( 'taxonomy' => 'product_cat');
$terms = get_the_terms($category->slug, 'product_cat', $args);

$count = count($terms); 
if ($count > 0) {
    foreach ($terms as $term) {
        // 判断当前术语ID是否等于当前分类ID
        if ($term->term_id === $category->term_id) {
            echo '<div class="prod-descr" style="direction:ltl;">';
            echo $term->description;
            echo '</div>';
        }
    }
}
?>  

代码说明

  • 方法一通过get_queried_object()直接获取当前页面的分类对象,无需遍历多个术语,更高效简洁。
  • 方法二在原循环中增加了ID匹配判断,只输出与当前分类ID一致的描述,过滤掉父分类内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 20:01:14