[Drupal] Get a list of other nodes that are related by taxonomy terms
Building on this snippet from Drupal to get related node items sharing the same taxonomy terms for 4.7, I have made it work for multiple terms. This snippet is for Drupal 5 and has been tested to work on 5.10.
The code will return a list view of 5 (changeable with $num_nodes) in an unordered list in a random format.
If you want to order the items you can edit the code to order the data in the SQL statement and take out lines 18 and 19.
<?php$num_nodes = 5;
$nid = arg(1);
$terms = taxonomy_node_get_terms($nid);
$items = array();
foreach($terms as $term) {
$sql = "SELECT DISTINCT n.title, n.nid
FROM {node} n
INNER JOIN {term_node} tn ON n.nid = tn.nid
WHERE n.status =1
AND tn.tid =".$term->tid."
AND n.nid !=".$nid."
LIMIT $num_nodes";
$result = db_query(db_rewrite_sql($sql));
while ($node = db_fetch_object($result)) {
$items[$node->nid] = l($node->title, 'node/'. $node->nid);
}
}
srand((float)microtime() * 1000000);
shuffle($items);
return theme('node_list', $items);?>
For Drupal 6, although I haven't tried this code, it should be the same except for line 3 which should be like this:
<?php$terms = taxonomy_node_get_terms(node_load($nid));?>
In Drupal 6, taxonomy_node_get_terms requires the whole node object rather than just the node ID (nid).