Using WordPress ‘get_previous_post()’ PHP function

The get_previous_post() WordPress PHP function retrieves the previous post that is adjacent to the current post.

Usage

$previous_post = get_previous_post($in_same_term, $excluded_terms, $taxonomy);

Parameters

  • $in_same_term (bool) Optional: Whether the post should be in the same taxonomy term. Default: false
  • $excluded_terms (int|string) Optional: Array or comma-separated list of excluded term IDs. Default: ”
  • $taxonomy (string) Optional: Taxonomy, if $in_same_term is true. Default: ‘category’

More information

See WordPress Developer Resources: get_previous_post()

Examples

Display previous post title

This example displays the title of the previous post.

$prev_post = get_previous_post();
if (!empty($prev_post)) {
  echo $prev_post->post_title;
}

Display previous post link

This example displays the link to the previous post.

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

Display previous post in the same category

This example displays the previous post only if it is in the same category as the current post.

$prev_post = get_previous_post(true);
if (!empty($prev_post)) {
  echo $prev_post->post_title;
}

Display previous post excluding certain categories

This example displays the previous post while excluding posts from categories with IDs 3 and 5.

$prev_post = get_previous_post(false, '3,5');
if (!empty($prev_post)) {
  echo $prev_post->post_title;
}

Display previous post in a custom taxonomy

This example displays the previous post in the same custom taxonomy term, using the taxonomy ‘my_custom_taxonomy’.

$prev_post = get_previous_post(true, '', 'my_custom_taxonomy');
if (!empty($prev_post)) {
  echo $prev_post->post_title;
}