theme development - Next and previous post link shows error in first and last post

I have added the Next and previous post link in a single.php file, I need to show the same categories post in the next a

I have added the Next and previous post link in a single.php file, I need to show the same categories post in the next and previous button. but it is showing error at first and last point

"Notice: Undefined offset: 5 in C:\xampp\htdocs\build-plugin\wp-content\themes\genesis\single.php on line 28" & "Notice: Undefined offset: -1 in C:\xampp\htdocs\build-plugin\wp-content\themes\genesis\single.php on line 29"

Shows error in this two lines

$prev_post = $ids[$index+1];
$next_post = $ids[$index-1];

Here is my code for next and previous button

$post_id = $post->ID; // Get current post ID
$cat = get_the_category(); 
$current_cat_id = $cat[0]->cat_ID; // Get current Category ID 

$args = array('category'=>$current_cat_id,'orderby'=>'post_date','order'=> 'DESC');
$posts = get_posts($args);
// Get IDs of posts retrieved by get_posts function
$ids = array();
foreach ($posts as $thepost) {
    $ids[] = $thepost->ID;
}
// Get and Echo the Previous and Next post link within same Category
$index = array_search($post->ID, $ids);
$prev_post = $ids[$index+1];
$next_post = $ids[$index-1];
?>

<?php if (!empty($prev_post)){ ?> <a class="previous-post" rel="prev" href="<?php echo get_permalink($prev_post) ?>"> <span class="meta-icon"><i class="fa fa-angle-left fa-lg"></i></span> Previous</a> <?php } ?>

<?php if (!empty($next_post)){ ?> <a class="next-post" rel="next" href="<?php echo get_permalink($next_post) ?>">Next <span class="meta-icon"><i class="fa fa-angle-right fa-lg"></i></span> </a> <?php } ?>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742289623a4415947.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信