WordPress at a glance

get_previous_post() WP 1.5.0

Retrieves the previous post that is adjacent to the current post. Return post as object.

To get the object of the next post, use get_next_post().

Works based on: get_adjacent_post()
✈ 1 time = 0.001871s = very slow | 50000 times = 2.00s = fast | PHP 7.1.5, WP 4.8.1

No Hooks.

Return

null/String/WP_Post. 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 a same taxonomy term.
Default: false
$excluded_terms(array/string)
Array or comma-separated list of excluded term IDs.
Default: ''
$taxonomy(string)
Taxonomy, if $in_same_term is true.
Default: 'category'

Examples

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

Code of get_previous_post: wp-includes/link-template.php VER 5.0.1

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

Related Functions

From tag: Relations (of posts terms...)

More from category: Navigation

No comments
    Hello, !     Log In . Register