在WordPress中调用指定分类文章有多种方法,以下是常用的几种方案:
1. 使用WP_Query(最灵活)
<?php
$args = array(
'post_type' => 'post', // 文章类型
'category_name' => 'news', // 分类别名
// 或使用分类ID
// 'cat' => 3,
'posts_per_page' => 5, // 显示数量
'orderby' => 'date', // 排序方式
'order' => 'DESC' // 排序顺序
);
$query = new WP_Query($args);
if ($query->have_posts()) :
while ($query->have_posts()) : $query->the_post();
?>
<article>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<div><?php the_excerpt(); ?></div>
</article>
<?php
endwhile;
wp_reset_postdata(); // 重置查询
else :
echo '没有找到相关文章';
endif;
?>
2. 使用get_posts(简单列表)
<?php
$posts = get_posts(array(
'category' => 3, // 分类ID
'numberposts' => 5
));
foreach ($posts as $post) :
setup_postdata($post);
?>
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<?php
endforeach;
wp_reset_postdata();
?>
3. 通过分类ID数组调用多个分类
<?php
$args = array(
'category__in' => array(3, 5, 7), // 包含这些分类
// 'category__and' => array(3, 5), // 同时属于这些分类
// 'category__not_in' => array(1), // 排除这些分类
'posts_per_page' => 6
);
$query = new WP_Query($args);
// ... 循环代码
?>
4. 在页面编辑器中调用(使用短代码)
在主题的 functions.php中添加:
// 创建短代码
function custom_category_posts_shortcode($atts) {
$atts = shortcode_atts(array(
'category' => 'news',
'count' => 5
), $atts);
ob_start();
$args = array(
'category_name' => $atts['category'],
'posts_per_page' => $atts['count']
);
$query = new WP_Query($args);
if ($query->have_posts()) {
echo '<ul>';
while ($query->have_posts()) {
$query->the_post();
echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
}
echo '</ul>';
}
wp_reset_postdata();
return ob_get_clean();
}
add_shortcode('category_posts', 'custom_category_posts_shortcode');
在文章或页面中使用:
[category_posts category="news" count="3"]
5. 通过分类别名调用
<?php
$args = array(
'category_name' => 'news,events', // 多个分类用逗号分隔
'posts_per_page' => 4
);
$query = new WP_Query($args);
?>
6. 高级查询示例(带分页)
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'cat' => 3,
'posts_per_page' => 10,
'paged' => $paged
);
$query = new WP_Query($args);
if ($query->have_posts()) :
while ($query->have_posts()) : $query->the_post();
// 内容显示
endwhile;
// 分页
the_posts_pagination(array(
'mid_size' => 2,
'prev_text' => '上一页',
'next_text' => '下一页',
));
wp_reset_postdata();
endif;
?>
使用建议
- WP_Query – 功能最全,适合复杂查询
- get_posts – 简单快速,适合简单列表
- 短代码 – 适合在编辑器中调用
- 记住重置 – 使用
wp_reset_postdata()避免影响主查询
获取分类信息
如果需要获取分类名称:
$category = get_category(3); // 通过ID
echo $category->name; // 分类名称
echo $category->slug; // 分类别名
echo $category->description; // 分类描述
选择最适合你需求的方法即可。


湘公网安备43020002000238