Next Post and Prev Post Finding From Post ids


Post Ids for all post including current post id

        foreach ($view_result as $entity) {
          $posts[$entity->nid->value] = $entity->nid->value; 
        }

         //call next and prev
         $pager = getAdjacentPost($posts,$currentpostId);

Function for adjacent post

function getAdjacentPost($posts,$currentpostID){
    $adjecentLinks = array();
    while (!in_array(key($posts), [$currentpostID])) {
        next($posts);
    }
    if (current($posts) !== false) {
        $nextPostId = next($posts);
        $adjecentLinks['next'] = $nextPostId;
        
    }
    reset($posts);
    while (!in_array(key($posts), [$currentpostID])) {
        next($posts);
    }
    if (current($posts) !== false) {
        $prevPostId = prev($posts);
        $adjecentLinks['prev'] = $prevPostId;
        
    }
  return($adjecentLinks);
}

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s