wordpress获取某分类下最新文章
时间 : 2023-12-10 18:46:02声明: : 文章内容来自网络,不保证准确性,请自行甄别信息有效性
最佳答案
在WordPress中,你可以使用`WP_Query`来获取某个分类下的最新文章。以下是一个示例代码:
```php
$args = array(
'post_type' => 'post',
'posts_per_page' => 5, // 获取最新5篇文章
'category_name' => 'your_category_slug', // 替换成你想要获取的分类的slug
);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
// 输出文章标题和链接
echo '<h2><a href="' . get_permalink() . '">' . get_the_title() . '</a></h2>';
// 输出文章内容
the_content();
}
} else {
// 如果没有找到文章
echo '没有相关文章。';
}
// 恢复原始查询
wp_reset_query();
替换`'your_category_slug'`为你想要获取的分类的slug,并将上述代码添加到你的WordPress主题的模板文件中,如`category.php`或`archive.php`。这将在页面上显示指定分类下的最新文章。
其他答案
要获取WordPress中某一分类下的最新文章,可以使用以下代码:
```php
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => 5, //显示的文章数量
'category_name' => 'category-slug', // 替换为要获取的分类别名
);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<p><?php the_excerpt(); ?>
<?php
}
} else {
echo '没有找到文章。';
}
wp_reset_postdata();
?>
在上述代码中,需要将`category-slug`替换为你要获取的分类别名,这样就可以获取该分类下最新的5篇文章。你可以根据需要调整`posts_per_page`参数来显示更多或更少的文章。
代码中,我们使用了`WP_Query`类来创建一个查询实例,并通过`post_type`参数指定查询的文章类型为`post`。然后,通过`category_name`参数指定要查询的分类别名。
在循环中,我们使用了`the_title()`函数来获取文章标题,使用`the_content()`函数来获取文章内容。
最后,我们使用`wp_reset_postdata()`函数重置查询后的结果,以便后续操作不受影响。
你可以将以上代码放在WordPress主题的模板文件中,比如`category.php`或`archive.php`中,以便在分类或存档页面显示最新文章。
https/SSL证书广告优选IDC>>
推荐主题模板更多>>
推荐文章