wp_get_recent_posts 获取最新文章
wp_get_recent_posts 函数在 WordPress 中是一个可以获取近期文章数组的函数,相较于其他的文章获取方式, wp_get_recent_posts 返回的将是一个数组而不是对象,所以在使用中对于一些新手或者是懒人,可能会更方便一些,下面我们就实例讲解一下这个函数。
描述
wp_get_recent_posts
英文解释很短,就不贴了,中文大概意思是:获取最新文章的函数。实际上这是一个 get_posts函数的再使用。描述的再好也木用,下面看使用。
使用/用法
<?php
wp_get_recent_posts( array $args, string $output )
?>
参数默认值
<?php $args = array( //获取的文章数量 'numberposts' => 10, //从第几篇开始获取 'offset' => 0, //分类的ID,如果不设置则显示全部分类 'category' => 0, //排序规则 (注1,下详) 'orderby' => 'post_date', //升、降序排列 'order' => 'DESC', //包括的文章ID 'include' => , //排除的文章ID 'exclude' => , //自定义字段名称 'meta_key' => , //自定义字段的值,配合上一个参数,来选择显示符合自定义字段数值的文章。 'meta_value' =>, //文章类型:文章或页面 'post_type' => 'post', //文章状态:草稿、已发布、隐藏文章等.... 'post_status' => 'draft, publish, future, pending, private', //是否使用过滤器 'suppress_filters' => true ); ?>
numberposts
整数,默认值:10
指定要返回的文章数量
offset
整数,默认为空
偏移数,例如设置为2,则从最新的第3篇文章开始返回数据。
category
整数,默认值:0
分类的ID,指定需要返回哪个分类的文章。
orderby
字符串值,默认值:post_date
按照哪个字段来排序,默认按照文章的发表时间排序。
order
字符串值,默认值:DESC
排序的方式
include
整数、数组或字符串值,默认为空
需要包含的文章ID,只有指定的这些文章才会被返回。
exclude
整数、数组或字符串值,默认为空
需要排除的文章ID,指定的这些文章不会被返回。
meta_key
字符串值,默认为空
自定义字段的名称,用于筛选文章
meta_value
字符串值,默认为空
自定义字段的值,用于筛选文章
post_type
字符串值,默认值:post
文章类型,默认为返回post类型的文章
post_status
字符串值,默认值:draft, publish, future, pending, private
文章的状态,可在以上值中只选择一种,例如设置为publish,则只返回公开的文章。
suppress_filters
布尔值,默认值:true
是否使用过滤器
wp_get_recent_posts()函数还有第二个参数:
$output
字符串值,默认值:ARRAY_A
- ARRAY_A:返回数组结构的数据;
- OBJECT:返回对象;
函数返回值
Array ( [0] => Array ( [ID] => 2436 [post_author] => 1 [post_date] => 2019-03-22 08:03:33 [post_date_gmt] => 2019-03-22 0:03:33 [post_content] => [post_title] => 文章标题 [post_excerpt] => [post_status] => publish [comment_status] => open [ping_status] => closed [post_password] => [post_name] => 文章别名 [to_ping] => [pinged] => [post_modified] => 2019-03-22 10:13:46 [post_modified_gmt] => 2019-03-22 02:13:46 [post_content_filtered] => [post_parent] => 0 [guid] => https://www.beizigen.com/?p=2436 [menu_order] => 0 [post_type] => post [post_mime_type] => [comment_count] => 0 [filter] => raw ), [1] => Array ( ...... ) ...... )
实例
因为跟 get_posts 的使用方法实在是很相似,所以就不给什么高深的例子了,简单的给一个官方的例子。
<h2>Recent Posts</h2>
<ul>
<?php
//获取最新文章
$recent_posts = wp_get_recent_posts();
//遍历出每一篇文章。
foreach( $recent_posts as $recent ){
echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a> </li> ';
}
wp_reset_query();
?>
</ul>
总结
注意:因为wp_get_recent_posts函数的返回值是一个数组,setup_postdata 函数理论上只能接受对象类型的变量,所以按照官方文档的解释是不能使用setup_postdata函数,装载到循环中使用的。因为用的不多,所以我也就没有去试,有兴趣的同学可以试一试看能否成功。所以说,如果使用 setup_postdata 函数的话,wp_get_recent_posts 函数不如 get_posts 函数使用起来方便。
注1:
‘author’ —— 按作者数值编号排序 ‘category’ —— 按类别数值编号排序 ‘content’ —— 按内容排序 ‘date’ —— 按创建日期排序 ‘ID’ —— 按文章编号排序 ‘menu_order’ —— 按菜单顺序排序。仅页面可用。 ‘mime_type’ —— 按MIME类型排序。仅附件可用。 ‘modified’ —— 按最后修改时间排序。 ‘name’ —— 按存根排序。 ‘parent’ —— 按父级ID排序 ‘password’ —— 按密码排序 ‘rand’ —— 任意排序结果 ‘status’ —— 按状态排序 ‘title’ —— 按标题排序 ‘type’ —— 按类型排序