The get_adjacent_post() WordPress PHP function retrieves the adjacent post, which can be either the next or previous post.
Usage
get_adjacent_post($in_same_term, $excluded_terms, $previous, $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: ”$previous(bool) – Optional. Whether to retrieve the previous post. Default: true$taxonomy(string) – Optional. Taxonomy, if$in_same_termis true. Default: ‘category’
More information
See WordPress Developer Resources: get_adjacent_post()
Examples
Get previous post in the same taxonomy
// Get previous post in the same taxonomy
$prev_post = get_adjacent_post(true, '', true, 'taxonomy_slug');
// If previous post exists, display a link to it
if (is_a($prev_post, 'WP_Post')) {
echo '<a href="' . get_permalink($prev_post->ID) . '">' . get_the_title($prev_post->ID) . '</a>';
}
Get next post in the same taxonomy
// Get next post in the same taxonomy
$next_post = get_adjacent_post(true, '', false, 'taxonomy_slug');
// If next post exists, display a link to it
if (is_a($next_post, 'WP_Post')) {
echo '<a href="' . get_permalink($next_post->ID) . '">' . get_the_title($next_post->ID) . '</a>';
}
Get previous post excluding specific terms
// Get previous post excluding term IDs 10 and 20
$prev_post = get_adjacent_post(false, '10,20', true);
// If previous post exists, display a link to it
if (is_a($prev_post, 'WP_Post')) {
echo '<a href="' . get_permalink($prev_post->ID) . '">' . get_the_title($prev_post->ID) . '</a>';
}
Get next post excluding specific terms
// Get next post excluding term IDs 10 and 20
$next_post = get_adjacent_post(false, '10,20', false);
// If next post exists, display a link to it
if (is_a($next_post, 'WP_Post')) {
echo '<a href="' . get_permalink($next_post->ID) . '">' . get_the_title($next_post->ID) . '</a>';
}
Get previous post in a custom taxonomy
// Get previous post in a custom taxonomy called 'custom_taxonomy'
$prev_post = get_adjacent_post(true, '', true, 'custom_taxonomy');
// If previous post exists, display a link to it
if (is_a($prev_post, 'WP_Post')) {
echo '<a href="' . get_permalink($prev_post->ID) . '">' . get_the_title($prev_post->ID) . '</a>';
}