如何在WordPress中基于当前文章所属分类展示关联文章列表
WordPress 单文章页同分类文章列表实现方案
适用场景
无需手动绑定推荐内容,文章所属分类变更后列表自动同步更新,完全匹配需求。
前置提醒
- 所有代码修改建议在子主题中操作,避免主题官方更新后自定义代码被覆盖
- 修改前提前备份对应模板文件,出错可快速回滚
方法1:直接修改单文章模板(灵活控制展示位置)
找到你当前主题的 single.php 模板文件,定位到「推荐话题」板块需要放置的位置,插入以下代码:
<?php // 仅单文章页生效 if (is_single()) { global $post; // 获取当前文章关联的所有分类 $post_cats = get_the_category($post->ID); if (!empty($post_cats)) { // 默认取第一个分类做查询,多分类场景可自行调整逻辑 $query_cat_id = $post_cats[0]->term_id; // 同分类文章查询参数 $related_args = array( 'cat' => $query_cat_id, 'post__not_in' => array($post->ID), // 排除当前正在浏览的文章 'posts_per_page' => -1, // -1 展示全部,需要限制数量改为对应数字即可 'ignore_sticky_posts' => 1, // 忽略置顶文章优先级 'orderby' => 'date', 'order' => 'DESC' // 按发布时间倒序,最新的在前 ); $related_query = new WP_Query($related_args); if ($related_query->have_posts()) { echo '<div class="recommend-topic">'; echo '<h3>推荐话题</h3>'; echo '<ul class="related-post-list">'; while ($related_query->have_posts()) { $related_query->the_post(); ?> <li> <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"> <?php the_title(); ?> </a> <!-- 要加发布时间、摘要可以在这里扩展 --> </li> <?php } echo '</ul></div>'; } // 重置主查询,避免影响页面其他内容的渲染 wp_reset_postdata(); } } ?>
后续你可以自行给 .recommend-topic、.related-post-list 加CSS样式调整展示效果。
方法2:钩子自动插入(无需修改原有模板结构)
如果不想改动原有 single.php 代码,可以把以下代码添加到主题的 functions.php 文件中,会自动拼接在文章正文的末尾:
add_filter('the_content', 'auto_insert_category_related_posts'); function auto_insert_category_related_posts($content) { // 仅前台单文章主查询场景生效,避免其他位置重复渲染 if (is_single() && in_the_loop() && is_main_query()) { global $post; $post_cats = get_the_category($post->ID); $related_html = ''; if (!empty($post_cats)) { $query_cat_id = $post_cats[0]->term_id; $related_args = array( 'cat' => $query_cat_id, 'post__not_in' => array($post->ID), 'posts_per_page' => -1, 'ignore_sticky_posts' => 1, 'orderby' => 'date', 'order' => 'DESC' ); $related_query = new WP_Query($related_args); if ($related_query->have_posts()) { $related_html .= '<div class="recommend-topic">'; $related_html .= '<h3>推荐话题</h3>'; $related_html .= '<ul class="related-post-list">'; while ($related_query->have_posts()) { $related_query->the_post(); $related_html .= sprintf( '<li><a href="%s" title="%s">%s</a></li>', esc_url(get_permalink()), esc_attr(get_the_title()), esc_html(get_the_title()) ); } $related_html .= '</ul></div>'; } wp_reset_postdata(); } // 把推荐列表拼接到原有文章内容后面 return $content . $related_html; } return $content; }
常见自定义调整
- 多分类展示:如果文章属于多个分类,要展示所有关联分类下的文章,把取分类ID的逻辑改成
$query_cat_ids = wp_list_pluck($post_cats, 'term_id');,同时把查询参数里的'cat' => $query_cat_id替换为'category__in' => $query_cat_ids - 数量限制:需要限制展示的文章数量,把
posts_per_page的值从-1改为对应数字即可,比如填8就是只展示最新的8篇 - 排序规则:需要按浏览量、点赞数排序,调整
orderby参数即可,配合对应统计字段使用
内容的提问来源于stack exchange,提问作者ZUH.
相关产品推荐
相关产品推荐

