Get the previous and next node in Drupal 7 with a simple query

Get the previous and next node in Drupal 7 with a simple query

While I’ve used the Previous/Next API, there is lots going on under the hood, including its on database index to search and query. I found it a little too heavy for my needs. I simply needed to get the next and previous nids when looking at a node. In my specific case, I wanted a link to the previous and next article when looking at an article node, so I only needed to return the nid. Here is my solution for finding next and previous nodes/pages in Drupal 7, in a single query, in a single function.

function mymodule_get_article($node, $type = 'next') {
  // fire up the query
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node') // look at nodes
    ->entityCondition('bundle', 'article') // article content-type
    ->propertyCondition('status', NODE_PUBLISHED) // only published ones of course
    ->range(0, 1) // only return one
    ->addMetaData('account', user_load(1)); // run the query as user 1.

  // determine if getting next or previous node
  if ($type == 'next') {
    $query->propertyCondition('created', $node->created, '<');
    $query->propertyOrderBy('created', 'DESC');
  }
  else { // previous
    $query->propertyCondition('created', $node->created, '>');
    $query->propertyOrderBy('created', 'ASC');
  }

  // maybe we only want to pull articles in the same category
  if ($items = field_get_items('node', $node, 'field_article_category')) {
    $tid = $items[0]['tid'];
    $query->fieldCondition('field_article_category', 'tid', $tid, '=')
  }

  // handle results
  $result = $query->execute();
  if (isset($result['node'])) {
    $next_nids = array_keys($result['node']);

    // if just need nid
    return $next_nids[0];

    // if need entire node
    return node_load($next_nids[0]);
  }
}

Comments are closed.