WordPress.org

Ready to get started?Download WordPress

Codex

Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Function Reference/get adjacent post

Contents

Description

Retrieve adjacent post. Can either be next or previous post.

Usage

<?php get_adjacent_post$in_same_term$excluded_terms$previous$taxonomy ?>

Parameters

$in_same_term
(boolean) (optional) Whether post should be in a same taxonomy term.
Default: false
$excluded_terms
(array or string) (optional) Array or comma-separated list of excluded term IDs.
Default: ''
$previous
(boolean) (optional) Whether to retrieve previous post.
Default: true
$taxonomy
(string) (optional) Taxonomy name, if $in_same_term is true.
Default: 'category'

Return Values

  • Post object if successful.
  • Null if global $post is not set.
  • Empty string if no corresponding post exists.

Examples

Link to previous post in the same taxonomy with Post Title for text.

 <?php $prev_post = get_adjacent_post( true, '', true, 'category_name' ); ?>
 <?php if ( !empty( $prev_post ) ): ?>
 	<a href="<?php echo $prev_post->guid; ?>"><?php echo $prev_post->post_title; ?></a>
 <?php endif; ?>

Link to next post in the same taxonomy with Post Title for text.

 <?php $next_post = get_adjacent_post( true, '', false, 'category_name' ); ?>
 <?php if ( !empty( $next_post ) ): ?>
 	<a href="<?php echo $next_post->guid; ?>"><?php echo $next_post->post_title; ?></a>
 <?php endif; ?>

Notes

  • Uses global: (object) $post
  • Uses global: (object) $wpdb

Filters

$adjacent is either 'previous' or 'next'.

  • "get_{$adjacent}_post_join":
    $join, $in_same_cat, $excluded_categories
  • "get_{$adjacent}_post_where":
    $wpdb->prepare("WHERE p.post_date $op %s AND p.post_type = %s AND p.post_status = 'publish' $posts_in_ex_cats_sql", $current_post_date, $post->post_type), $in_same_cat, $excluded_categories
  • "get_{$adjacent}_post_sort":
    "ORDER BY p.post_date $order LIMIT 1"

Change Log

Since: 2.5.0

Source File

get_adjacent_post() is located in wp-includes/link-template.php.

Related

See also index of Function Reference and index of Template Tags.