WordPress获取当前文章上一篇文章的信息函数get_previous_post()

wordpress 函数 get_previous_post() 常置于文章内容页面,用于判断是否存在上一篇文章或者限制返回当前文章相同分类的上一篇文章。其实 get_previous_post() 函数除此之外,还可以获取上一篇文章的内容信息,如获取上篇文章ID、标题、内容、摘要、作者等。

函数代码

<?php 
	get_previous_post( boolean $in_same_cat, string $excluded_categories )
?>

参数说明

  • $in_same_cat – 布尔型,默认值:false,如果为true,则输出与当前文章相同分类下的上一篇文章。
  • $excluded_categories – 字符串,默认为空,要排除的分类ID

函数返回值

WP_Post Object ( 
	[ID] => 214 //文章ID
	[post_author] => 1 //文章作者ID
	[post_date] => 2021-05-28 01:49:49 //文章发布服务器时间
	[post_date_gmt] => 2021-05-28 17:49:49 //文章发布的格林威治时间
	[post_content] => 专业的Wordpress主题模板开发商,有着多年WP主题开发经验,提供高品质的Wordpress主题模板! //文章内容 
	[post_title] => HiTheme主题 //文章标题
	[post_excerpt] =>  //文章摘要
	[post_status] => publish //文章状态
	[comment_status] => open //文章评论状态
	[ping_status] => closed //文章Ping状态
	[post_password] => //文章密码
	[post_name] => boke8 //文章别名 
	[to_ping] => //被Ping的
	[pinged] => //已Ping的
	[post_modified] => 2017-09-24 01:49:49 
	[post_modified_gmt] => 2017-09-23 17:49:49 
	[post_content_filtered] => //过滤后的文章内容
	[post_parent] => 0 //文章父级ID
	[guid] => https://www.boke8.net/?p=1 //文章唯一标识符,文章原始URL
	[menu_order] => 0 //菜单排序
	[post_type] => post //文章类型
	[post_mime_type] => //文章mime类型
	[comment_count] => 0 //文章评论数量
	[filter] => raw //过滤器信息
)

使用示例

获取上一篇文章ID

<?php 
	$prevPost = get_previous_post();
	echo $prevPost->ID;
?>

获取同分类上一篇文章信息

<?php 
	$prevPost = get_previous_post(true);
	print_r($prevPost);
?>

函数位置:

wp-includes/link-template.php