• i found this code to show next and prev post link in same category, the problem Is the following:

    I have found this code to display NEXT and PREVIOUS link to posts in the same category.

    I have 20 posts. If I start browsing from the 1st of the 20, all goes fine. “Previous ” and “Next” links work perfectly.

    But If I click post number 15: the problem occurs, the previous link disappears and the next post link instead of linking to post 16th (the real next one) links to the 1st post of the category.

    Can you advice what is wrong in my code? I use it single-loop.php of the theme *twentyten*.

    $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 = $ids[$thisindex-1];
        $nextid = $ids[$thisindex+1];
    
        if (!empty($previd)){
        ?>
        <a rel="prev" href="<?php echo get_permalink($previd) ?>">Previous</a>
        <?php
        }
        if (!empty($nextid)){
        ?>
        <a rel="next" href="<?php echo get_permalink($nextid) ?>">Next</a>
        <?php
        }
        ?>

  • The topic ‘Next prev post link within same category’ is closed to new replies.