Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Previous, next posts for single post
<?php
global $post;
$post_id = $post->ID; // current post ID
$cat = get_the_category();
$current_cat_id = $cat[0]->cat_ID; // current category ID
$args = array(
'category' => $current_cat_id,
'orderby' => 'post_date',
'order' => 'DESC'
);
$posts = get_posts( $args );
// get IDs of posts retrieved from get_posts
$ids = array();
foreach ( $posts as $the_post ) {
$ids[] = $the_post->ID;
}
// get and echo previous and next post in the same category
$this_index = array_search( $post_id, $ids );
$prev_id = $ids[ $this_index - 1 ];
$next_id = $ids[ $this_index + 1 ];
if ( ! empty( $prev_id ) ) {
?><a rel="prev"
href="<?php echo get_permalink( $prev_id ) ?>"><?php _e( 'Prev post', 'kleo' ); ?></a><?php
}
if ( ! empty( $next_id ) ) {
?><a rel="next"
href="<?php echo get_permalink( $next_id ) ?>"><?php _e( 'Next post', 'kleo' ); ?></a><?php
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment