Using WordPress ‘get_next_post()’ PHP function

The get_next_post WordPress PHP function retrieves the next post that is adjacent to the current post.

Usage

get_next_post($in_same_term, $excluded_terms, $taxonomy);

Parameters

  • $in_same_term (bool) Optional: Whether 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’. Default: ‘category’

More information

See WordPress Developer Resources: get_next_post

Examples

Basic usage of get_next_post

Display the title of the next post.

$next_post = get_next_post();
if ( is_a( $next_post , 'WP_Post' ) ) {
  echo '<a href="' . get_permalink( $next_post->ID ) . '">' . get_the_title( $next_post->ID ) . '</a>';
}

Get next post in the same tag

Display a link to the next post in the same tag.

$next_post = get_next_post(true, '', 'post_tag');
if ( is_a( $next_post , 'WP_Post' ) ) {
  echo '<a href="' . get_permalink( $next_post->ID ) . '">Back</a>';
}

Exclude specific categories

Exclude categories with IDs 5 and 15 when getting the next post.

$next_post = get_next_post(false, '5,15');
if ( is_a( $next_post , 'WP_Post' ) ) {
  echo '<a href="' . get_permalink( $next_post->ID ) . '">' . get_the_title( $next_post->ID ) . '</a>';
}

Get next post in a custom taxonomy

Display the next post in the same custom taxonomy term, where the taxonomy is ‘genre’.

$next_post = get_next_post(true, '', 'genre');
if ( is_a( $next_post , 'WP_Post' ) ) {
  echo '<a href="' . get_permalink( $next_post->ID ) . '">' . get_the_title( $next_post->ID ) . '</a>';
}

Check if there’s a next post before displaying the link

Only display the link to the next post if there’s one available.

$next_post = get_next_post();
if ( is_a( $next_post , 'WP_Post' ) ) {
  echo '<a href="' . get_permalink( $next_post->ID ) . '">' . get_the_title( $next_post->ID ) . '</a>';
} else {
  echo "There are no more posts.";
}