related nodes to the current node by taxonomy term

Last modified: March 27, 2008 - 22:17

Use the code below to build a custom block that shows the related nodes to the current node by taxonomy term. For example: If the current node in display has a taxonomy term "fish", a bunch of links that link to nodes that have the "fish" term is to be shown in a block on the page.

<?php
if (arg(0) == 'node' && is_numeric(arg(1)) && is_null(arg(2))) {
 
$nid = (int)arg(1);
 
$terms = taxonomy_node_get_terms($nid);
 
$output = "<ul>";
  foreach(
$terms as $term){
   
$sql = "SELECT n.title, n.nid FROM {node} n INNER JOIN {term_node} tn ON n.nid = tn.nid WHERE tn.tid = $term->tid AND n.nid != $nid LIMIT 5";  
   
$result = db_query(db_rewrite_sql($sql));
    if (
db_num_rows($result)) {
     
$output .="<li>$term->name</li><ul>";
      while (
$anode = db_fetch_object($result)) {
       
$output .= "<li>".l($anode->title, "node/$anode->nid")."</li>";
      }  
     
$output.="</ul>";
    }
  }
 
$output .= "</ul>";
  return
$output;
}
?>

Here is a simpler list format without the Term name, sorted by date, filtered for published and images, and is rendered correctly by the theme.

<?php
if (arg(0) == 'node' && is_numeric(arg(1)) && is_null(arg(2))) {
 
$nid = (int)arg(1);
 
$terms = taxonomy_node_get_terms($nid);
 
$output = "<ul>";
  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 AND n.type <> 'image' ORDER BY n.created DESC LIMIT 6";
   
$result = db_query(db_rewrite_sql($sql));
    if (
db_num_rows($result)) {
      while (
$anode = db_fetch_object($result)) {
       
$output = node_title_list($result);
      }
    }
  }
  return
$output;
}
?>

Note 1- adapted from forum

Note 2- Drupal 6 compatible version here

 
 

Drupal is a registered trademark of Dries Buytaert.