获取最近文章, 可以使用如下函数实现
wp_get_recent_posts
这个函数的基本格式为
wp_get_recent_posts( array $args, string $output )
其中, args表示参数, output表示返回值格式一般省略
args的属性值及其默认值如下
- ‘numberposts’ => 10 (文章数量)
- ‘offset’ => 0 (从第几篇开始)
- ‘category’ => 0 (分类目录id)
- ‘orderby’ => ‘post_date’ (排序字段, 默认是时间)
- ‘order’ => ‘DESC’, (排序规则, 默认是降序)
- ‘include’ => ”, (指定包含文章id)
- ‘exclude’ => ”, (排除文章id)
- ‘meta_key’ => ”, (自定义筛选字段名称)
- ‘meta_value’ =>”, (自定义筛选字段的值)
- ‘post_type’ => ‘post’, (文章类型)
- ‘post_status’ => ‘draft, publish, future, pending, private’, (文章状态)
- ‘suppress_filters’ => true (是否使用过滤器)
使用案例
打印最新的 5 篇文章, 且文章前显示序号
<h2>最近文章</h2>
<ol>
<?php
$recent_posts = wp_get_recent_posts('numberposts=5&post_status=publish');
foreach( $recent_posts as $recent ){
echo '<li><a href="' . get_permalink($recent["ID"]) . '">' . $recent["post_title"] . '</a></li>';
}
wp_reset_query();
?>
</ol>
获取随机文章
随机文章, 可以通过修改上述代码的排序, 也就是 orderby = rand
实现代码如下: (它并非是最新文章的随机, 而是全部文章的随机)
<h2>随机文章</h2>
<ol>
<?php
$recent_posts = wp_get_recent_posts('numberposts=5&post_status=publish&orderby=rand');
foreach( $recent_posts as $recent ){
echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="'.$recent["post_title"].'">' . $recent["post_title"] . '</a></li>';
}
wp_reset_query();
?>
</ol>