Drupal node siblings

Sometimes it is necessary to find out the next or previous Drupal node given the current node id.

How can we do this?

This is one solution for this problem.

The function below accepts the following arguments:

  • $nid - current Drupal node id
  • $dir - direction of the sibling
  • $tid - Drupal taxonomy term id in case we want to search for siblings which have a specific term id
  • $promote - limit the siblings to the Drupal promoted nodes only

  1. <?php
  2. function _node_sibling($nid, $dir = 'next', $tid = FALSE, $promote = FALSE) {
  3. $tid_sql = (is_numeric($tid)) ? "INNER JOIN {term_node} tn ON(n.nid = tn.nid AND n.vid = tn.vid AND tn.tid = $tid)" : '';
  4. $promote_sql = ($promote === TRUE) ? 'AND n.promote = 1' : '';
  5.  
  6. $sql = <<<SQL
  7. SELECT n.nid FROM {node} n
  8. %s
  9. WHERE n.nid %s %d
  10. AND n.type = "blog"
  11. AND n.status=1
  12. AND n.moderate = 0
  13. %s
  14. ORDER BY n.created %s LIMIT 1
  15. SQL;
  16.  
  17. $sql = sprintf($sql, $tid_sql, ($dir == 'previous' ? '<' : '>'), $nid, $promote_sql, ($dir == 'previous' ? 'DESC' : 'ASC'));
  18. $result = db_query($sql);
  19. return ($result && db_affected_rows() == 1) ? db_result($result) : false;
  20. }
  21. ?>

I hope you find this function useful!

Good luck!

  • Drupal Modules: