Using WordPress ‘get_adjacent_post_link()’ PHP function

The get_adjacent_post_link() WordPress PHP function retrieves the adjacent post link, which can be either the next post link or the previous post link.

Usage

echo get_adjacent_post_link($format, $link, $in_same_term, $excluded_terms, $previous, $taxonomy);

Parameters

  • $format (string): Link anchor format.
  • $link (string): Link permalink format.
  • $in_same_term (bool, optional): Whether the link should be in the same taxonomy term. Default is false.
  • $excluded_terms (int|string, optional): Array or comma-separated list of excluded terms IDs. Default is ''.
  • $previous (bool, optional): Whether to display link to previous or next post. Default is true.
  • $taxonomy (string, optional): Taxonomy, if $in_same_term is true. Default is 'category'.

More information

See WordPress Developer Resources: get_adjacent_post_link

Examples

Basic usage

Display the next post link.

echo get_adjacent_post_link('%link', 'Next Post: %title', false, '', false);

Display previous post link

Display the previous post link.

echo get_adjacent_post_link('%link', 'Previous Post: %title', false, '', true);

Display the next post link within the same category.

echo get_adjacent_post_link('%link', 'Next Post in Category: %title', true, '', false, 'category');

Exclude specific terms

Display the next post link, excluding posts from specific categories (in this case, categories with IDs 4 and 7).

echo get_adjacent_post_link('%link', 'Next Post: %title', false, '4,7', false);

Using custom taxonomy

Display the next post link within the same custom taxonomy (e.g., ‘portfolio’).

echo get_adjacent_post_link('%link', 'Next Project: %title', true, '', false, 'portfolio');