0

I am trying to display two links, previous and next post in the current category.

What I have so far works fine, but how do I make the next link to the first post when on the last post and vice-versa, make previous link to the last post when on the first?

<?php
    $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 $thepost ) {
    $ids[] = $thepost->ID;
}
// get and echo previous and next post in the same category
$thisindex = array_search( $post_id, $ids );
$previd    = isset( $ids[ $thisindex - 1 ] ) ? $ids[ $thisindex - 1 ] : 0;
$nextid    = isset( $ids[ $thisindex + 1 ] ) ? $ids[ $thisindex + 1 ] : 0;

if ( $nextid) {
    // Left links to previous post
    ?>
        <a href="<?php echo get_permalink($previd) ?>"><?php echo get_the_title($previd) ?></a>
    <?php
}
else if ( $previd ) {
    // Right links to next post
    ?>
        <a href="<?php echo get_permalink($nextid) ?>"><?php echo get_the_title($nextid) ?></a>
    <?php
}

?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.