Using WordPress ‘next_post_link()’ PHP function

The next_post_link() WordPress PHP function displays the next post link that is adjacent to the current post.

Usage

next_post_link($format, $link, $in_same_term, $excluded_terms, $taxonomy);

Parameters

  • $format (string) – Optional. Link anchor format. Default: ‘« %link’.
  • $link (string) – Optional. Link permalink format. Default: ‘%title’.
  • $in_same_term (bool) – Optional. Whether the link 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: next_post_link()

Examples

Bold Post Title As Link

Displays link with the next chronological post’s title wrapped in ‘strong’ tags (“My Next Post Title”).

next_post_link('<strong>%link</strong>');

Within Same Category, Excluding One

Displays link to the next post in the same category, as long as it is not in category 13 (the category ID #). You can change the number to any category you wish to exclude. Exclude multiple categories by using “,” as a delimiter.

next_post_link('%link', 'Next post in category', true, '13');

Within Same Custom Taxonomy

Displays link to the next post in the same custom taxonomy term.

next_post_link('%link', 'Next post in taxonomy', true, '', 'my_custom_taxonomy');

Replace Next/Previous Post Text

Changes the default ‘« %link’ format to just the post title, removing the default double arrows.

previous_post_link('%link', '%title');
next_post_link('%link', '%title');

You can replace %title with alternative text.

Custom Pagination with Bootstrap

If you use Bootstrap, this example shows how to modify the class (a) in a custom pagination.

In the single.php file:

<ul class="pagination justify-content-center mb-4">
    <li class="page-item">
        <?php next_post_link('%link', '<i class="fas fa-arrow-right"></i> %title'); ?>
    </li>
    <li class="page-item">
        <?php previous_post_link('%link', '%title <i class="fas fa-arrow-left"></i>'); ?>
    </li>
</ul>

In the functions.php file:

function wpdocs_add_post_link($html) {
    $html = str_replace('<a ', '<a class="page-link" ', $html);
    return $html;
}
add_filter('next_post_link', 'wpdocs_add_post_link');
add_filter('previous_post_link', 'wpdocs_add_post_link');