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
<?php function _node_sibling($nid, $dir = 'next', $tid = FALSE, $promote = FALSE) { $tid_sql = (is_numeric($tid)) ? "INNER JOIN {term_node} tn ON(n.nid = tn.nid AND n.vid = tn.vid AND tn.tid = $tid)" : ''; $promote_sql = ($promote === TRUE) ? 'AND n.promote = 1' : ''; $sql = <<<SQL SELECT n.nid FROM {node} n %s WHERE n.nid %s %d AND n.type = "blog" AND n.status=1 AND n.moderate = 0 %s ORDER BY n.created %s LIMIT 1 SQL; $sql = sprintf($sql, $tid_sql, ($dir == 'previous' ? '<' : '>'), $nid, $promote_sql, ($dir == 'previous' ? 'DESC' : 'ASC')); $result = db_query($sql); return ($result && db_affected_rows() == 1) ? db_result($result) : false; } ?>
I hope you find this function useful!
Good luck!
