WordPress点击子分类仅展示对应文章的实现问题
问题分析与解决方案
原代码的核心问题是遍历了自定义文章类型的所有分类及术语,完全忽略了当前页面的子分类参数,导致无论点击哪个子分类,都会输出所有分类下的文章。
正确的做法是直接获取当前页面对应的子分类术语,仅查询该术语下的ortemp类型文章,修正后的代码如下:
<?php $post_type = 'ortemp'; // 获取当前页面的分类术语对象 $current_term = get_queried_object(); // 校验当前术语是否属于目标分类法 if ($current_term && $current_term->taxonomy === 'categorys') { $customposts = new WP_Query(array( 'posts_per_page' => -1, 'post_type' => $post_type, 'tax_query' => array( array( 'taxonomy' => $current_term->taxonomy, 'terms' => $current_term->term_id, 'field' => 'term_id', 'include_children' => false, // 可选:是否包含子分类的文章,按需调整 ) ) )); if ($customposts->have_posts()) : echo '<div id="activities_categories"><ul>'; while ($customposts->have_posts()) : $customposts->the_post(); echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>'; endwhile; echo '</ul></div>'; // 重置查询,避免干扰后续模板逻辑 wp_reset_postdata(); else : echo '<p>该分类下暂无文章</p>'; endif; } ?>
关键说明:
get_queried_object():WordPress在分类归档页会自动返回当前访问的分类术语,直接用它就能拿到点击的子分类信息,无需遍历所有分类。- 新增
post_type参数:确保仅查询ortemp类型的文章,避免默认查询普通文章。 wp_reset_postdata():重置查询上下文,防止全局文章变量被污染。include_children:如果不需要展示当前子分类下的嵌套子分类文章,设为false,反之设为true。
内容的提问来源于stack exchange,提问作者thefreenor
相关产品推荐
相关产品推荐

