2
votes

I am using this code but once i click on the next post/previous post link i am redirected to the next post/ previous post of the different category

 previous_post_link('%link', 'Prev post in category', $in_same_term = true);
 next_post_link('%link', 'Next post in category', $in_same_term = true);

I am trying to fix my issue using this article http://codex.wordpress.org/Function_Reference/next_post_link

Thanks

2

2 Answers

2
votes

Here is the code to get category based previous and next links on posts

$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
}
?>
0
votes

You can do this...

Just change the argument $in_same_term as true..

previous_post_link( $format, $link, $in_same_term = false, $excluded_terms = '', $taxonomy = 'category' );