
本文介绍如何使用 wordpress 的 `get_posts()` 函数,通过分类名称(而非 id)精准获取指定分类下的所有已发布文章,并生成带分类名标题和文章链接的前端展示结构。
在 WordPress 主题或自定义页面模板中,若需根据分类名称(如 'fruit' 或 'vegetables')动态拉取该分类下的全部公开文章,推荐使用核心函数 get_posts() 并传入 'category_name' 参数——它接受分类的 slug(即 URL 友好型别名),而非 ID 或中文名称,这是关键前提。
以下是一个完整、可直接复用的示例代码:
<?php
// 指定目标分类的 slug(注意:必须是分类的 slug,不是显示名称)
$category_slug = 'vegetables'; // 例如:'fruit'、'vegetables'
// 查询该分类下所有已发布的文章
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'category_name' => $category_slug,
'posts_per_page' => -1, // 获取全部,也可设为具体数字(如 6)
'orderby' => 'date',
'order' => 'DESC'
);
$posts = get_posts($args);
// 若存在文章,则渲染列表
if (!empty($posts)) {
$category = get_category_by_slug($category_slug);
$category_name = $category ? $category->name : ucfirst($category_slug);
?>
<section class="category-posts-section">
<h2><?php echo esc_html($category_name); ?></h2>
<div class="posts-grid">
<?php foreach ($posts as $post) : setup_postdata($post); ?>
<article class="post-card">
<h3>
<a href="<?php echo esc_url(get_permalink($post)); ?>">
<?php echo esc_html($post->post_title); ?>
</a>
</h3>
<p class="post-excerpt">
<?php echo wp_trim_words($post->post_excerpt ?: $post->post_content, 20); ?>
</p>
</article>
<?php endforeach; ?>
</div>
</section>
<?php
wp_reset_postdata(); // ⚠️ 重要:重置全局 $post 对象,避免影响后续查询
} else {
echo '<p>暂无该分类下的文章。</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/ai/1220" title="Logo Diffusion"><img
src="https://img.php.cn/upload/ai_manual/000/000/000/175680124852152.png" alt="Logo Diffusion" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/ai/1220" title="Logo Diffusion">Logo Diffusion</a>
<p>利用生成式AI技术,在几秒钟内创建Logo</p>
</div>
<a href="/ai/1220" title="Logo Diffusion" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div>';
}
?>✅ 关键说明与注意事项:
- category_name 参数值必须是分类的 slug(如 fruits-and-vegetables),而非后台设置的中文名称(如“水果与蔬菜”)。可通过「文章 → 分类目录」编辑分类时 URL 中的 tag_ID= 后数字,或查看分类编辑页的「别名」字段确认。
- 若需同时查询多个分类,应改用 'cat'(ID 列表,如 'cat' => '3,5,8')或 'category__in'(数组形式),category_name 仅支持单个 slug。
- get_posts() 默认不执行全局 $post 赋值,因此循环中需手动调用 setup_postdata($post) 才能正常使用 the_permalink()、the_title() 等模板标签;使用完毕后务必调用 wp_reset_postdata() 恢复上下文。
- 如需 SEO 友好链接或更灵活的分类关系(如多级分类、自定义分类法),建议升级为 WP_Query 并配合 tax_query,但对基础场景,get_posts() 更简洁安全。
掌握这一模式后,你即可轻松实现“点击分类名跳转至其专属文章聚合页”,大幅提升内容导航体验与主题灵活性。








