显示来自同一类别的帖子,当用户单击下一个/上一个帖子在单个.php页面


Display the posts from the same category when user clicks on next/previous post in single.php page

我正在使用这个代码,但是一旦我点击下一个帖子/上一个帖子链接,我被重定向到不同类别的下一个帖子/上一个帖子

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

我正在尝试解决我的问题使用这篇文章http://codex.wordpress.org/Function_Reference/next_post_link

谢谢

下面是获取基于文章上一个和下一个链接的类别的代码

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

你可以这样做…

只需将参数$in_same_term更改为true.

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

它的工作分类请检查previous_post_link('%link', ' Privious',$in_same_term = true);类别("%链接","下一个",美元in_same_term = true),