get_previous_post()WP 1.5.0

Retrieves the previous post (as object) from the specified taxonomy (the default is category).

Use get_next_post(), to get the object of the next post.

1 time — 0.001871 sec (very slow) | 50000 times — 2.00 sec (fast) | PHP 7.1.5, WP 4.8.1

No Hooks.

Return

WP_Post|null|String. Post object if successful. Null if global $post is not set. Empty string if no corresponding post exists.

Usage

get_previous_post( $in_same_term, $excluded_terms, $taxonomy );
$in_same_term(true|false)
Whether post should be in the same taxonomy term.
Default: false
$excluded_terms(int[]|string)
Array or comma-separated list of excluded term IDs.
Default: ''
$taxonomy(string)
Taxonomy, if $in_same_term is true.
Default: 'category'

Examples

0

#1 Get the previous post and output a link to it (demonstration of how the function works).

$prev_post = get_previous_post();
echo '<a href="' . get_permalink( $prev_post ) . '">'. esc_html($prev_post->post_title) .'</a>';

To get such a link, it is more convenient to use the function: previous_post_link().

Changelog

Since 1.5.0 Introduced.

get_previous_post() code WP 6.5.2

function get_previous_post( $in_same_term = false, $excluded_terms = '', $taxonomy = 'category' ) {
	return get_adjacent_post( $in_same_term, $excluded_terms, true, $taxonomy );
}