admin管理员组

文章数量:1335580

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

本文标签: theme developmentNext and previous post link shows error in first and last post