WordPress获取上一篇文章函数:get_previous_post

WordPress函数get_previous_post用于获取上一篇文章,可以限制返回相同分类的上一篇文章,需要用在文章页面模板里。

get_previous_post( boolean $in_same_cat, string $excluded_categories )

函数参数

$in_same_cat

布尔值,默认值:false

如果为true,则输出与当前文章相同分类下的上一篇文章。

$excluded_categories

字符串值,默认为空

要排除的分类ID

函数返回值

函数返回值示例:

WP_Post Object (
	[ID] => 2283
	[post_author] => 1
	[post_date] => 2019-09-13 21:39:48
	[post_date_gmt] => 2019-09-13 13:39:48
	[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-09-13 21:39:48
	[post_modified_gmt] => 2019-09-13 13:39:48
	[post_content_filtered] =>
	[post_parent] => 0
	[guid] => https://www.beizigen.com/?p=2283
	[menu_order] => 0
	[post_type] => post
	[post_mime_type] =>
	[comment_count] => 0
	[filter] => raw
)

函数使用示例

输出上一篇文章链接,这里链接地址没有直接使用guid的值,而是使用get_permalink()函数获取伪静态链接。

<?php
$prev_post = get_previous_post();
if (!empty( $prev_post )) {
	echo '<a href="' . get_permalink($prev_post) . '">' . $prev_post->post_title . '</a>';
}
?>

扩展阅读

get_previous_post()函数位于:wp-includes/link-template.php

相关函数:

Typora