WordPress获取最新文章函数:wp_get_recent_posts

WordPress函数wp_get_recent_posts用于获取最新文章,包括文章的标题、别名、状态、发表时间、修改时间、内容等信息。

wp_get_recent_posts( array $args, string $output )

函数参数

$args

数组

wp_get_recent_posts()函数$args参数默认的值如下:

$args = array(
	'numberposts' => 10,
	'offset' => 0,
	'category' => 0,
	'orderby' => 'post_date',
	'order' => 'DESC',
	'include' => '',
	'exclude' => '',
	'meta_key' => '',
	'meta_value' =>'',
	'post_type' => 'post',
	'post_status' => 'draft, publish, future, pending, private',
	'suppress_filters' => true
);

wp_get_recent_posts()函数$args参数可用的值如下:

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 (
		......
	)
		......
)

函数使用示例

以下代码会输出10篇最新文章列表,注意在输出结果之后,使用了wp_reset_query()函数来重置循环,避免下一个查询出现错误。

<h2>最新文章</h2>
<ul>
<?php
	$recent_posts = wp_get_recent_posts();
	foreach( $recent_posts as $recent ){
		echo '<li><a href="' . get_permalink($recent["ID"]) . '">' . $recent["post_title"] . '</a></li>';
	}
	wp_reset_query();
?>
</ul>

扩展阅读

wp_get_recent_posts()函数位于:wp-includes/post.php

相关函数:

阿里云