Using WordPress ‘adjacent_post_link()’ PHP function

The adjacent_post_link() WordPress PHP function displays the link to the adjacent (next or previous) post. This can be particularly useful when you’re navigating through your blog or article series.

Usage

Here’s a simple way to use adjacent_post_link(). This code displays a link to the next post on your WordPress site:

adjacent_post_link('« %link');

In the above, ‘« %link’ is the format string where ‘%link’ will be replaced by the link of the next post.

Parameters

  • $format (string) Required: This is the link anchor format.
  • $link (string) Required: This is the link permalink format.
  • $in_same_term (bool) Optional: Indicates if the link should be in the same taxonomy term. Defaults to false.
  • $excluded_terms (int | string) Optional: An array or comma-separated list of excluded category IDs. Defaults to ” (empty string).
  • $previous (bool) Optional: Specifies whether to display link to previous or next post. Defaults to true.
  • $taxonomy (string) Optional: Specifies the taxonomy, if $in_same_term is true. Default is ‘category’.

More information

See WordPress Developer Resources: adjacent_post_link()

This function was implemented in WordPress 2.5. It is not depreciated and you can find its source code in wp-includes/link-template.php.

Examples

Displaying a Link to the Next Post

In this example, we use adjacent_post_link() to display a link to the next post.

adjacent_post_link( '%link', 'Next post: %title' );

The ‘%link’ will be replaced by the actual link, and ‘%title’ will be replaced by the title of the next post.

Displaying a Link to the Previous Post

To display a link to the previous post, we set the $previous parameter to true.

adjacent_post_link( '%link', 'Previous post: %title', true );

Excluding Specific Categories

If you want to exclude certain categories, use the $excluded_terms parameter.

adjacent_post_link( '%link', 'Next in category: %title', false, '1,3' );

In this case, posts in categories with IDs 1 and 3 will be excluded.

Using a Specific Taxonomy

To use a specific taxonomy, set $in_same_term to true and specify the taxonomy in the $taxonomy parameter.

adjacent_post_link( '%link', 'Next in taxonomy: %title', true, '', false, 'custom-taxonomy' );

This will display a link to the next post in the same ‘custom-taxonomy’.

To display a link to the next post in the same taxonomy term, set $in_same_term to true.

adjacent_post_link( '%link', 'Next in term: %title', true );

This will display a link to the next post in the same term of the default ‘category’ taxonomy.