Created
July 23, 2016 14:11
-
-
Save vladimirlukyanov/8f9054f02da334cc9819fd33f14c791f to your computer and use it in GitHub Desktop.
Previous, next posts for single post
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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