Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vladimirlukyanov/8f9054f02da334cc9819fd33f14c791f to your computer and use it in GitHub Desktop.
Save vladimirlukyanov/8f9054f02da334cc9819fd33f14c791f to your computer and use it in GitHub Desktop.
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