基本方法:使用WP_Query
在WordPress中调用特定分类下的文章,最常用的方法是使用WP_Query
类。以下是基本代码示例:
<?php
$args = array(
'category_name' => '你的分类别名', // 使用分类别名
// 或使用分类ID
// 'cat' => 5, // 5是分类ID
'posts_per_page' => 10 // 显示文章数量
);
$query = new WP_Query($args);
if ($query->have_posts()) :
while ($query->have_posts()) : $query->the_post();
// 显示文章内容
the_title('<h2>', '</h2>');
the_excerpt();
endwhile;
wp_reset_postdata();
else :
echo '没有找到相关文章';
endif;
?>
通过分类ID调用
如果你知道分类的ID,可以使用cat
参数:
$args = array(
'cat' => 5, // 5是分类ID
'posts_per_page' => 5
);
通过分类别名调用
如果你知道分类的别名(slug),可以使用category_name
参数:
$args = array(
'category_name' => 'news', // news是分类别名
'posts_per_page' => 5
);
调用多个分类下的文章
如果需要调用多个分类下的文章,可以使用category__in
参数:
$args = array(
'category__in' => array(2, 6), // 2和6是分类ID
'posts_per_page' => 5
);
排除特定分类
如果需要排除某些分类,可以使用category__not_in
参数:
$args = array(
'category__not_in' => array(3), // 排除ID为3的分类
'posts_per_page' => 5
);
使用get_posts函数
除了WP_Query
,还可以使用get_posts
函数:
$posts = get_posts(array(
'category' => 5, // 分类ID
'numberposts' => 5
));
foreach ($posts as $post) {
setup_postdata($post);
the_title('<h2>', '</h2>');
the_excerpt();
}
wp_reset_postdata();
在页面模板中使用
如果你想在页面模板中调用特定分类的文章,可以将上述代码放入你的模板文件中(如page-custom.php)。
注意事项
- 使用完毕后记得调用
wp_reset_postdata()
,以免影响主循环 - 分类别名是区分大小写的
- 可以通过WordPress后台的”文章→分类目录”查看分类ID和别名
通过以上方法,你可以灵活地在WordPress中调用任何分类下的文章,并根据需要自定义显示方式。