Display related nodes in Drupal
I just hacked the following code into my node.tpl.php to display five possible related nodes beneath each story. There also is a module doing this, however, I wanted to reuse the build in search, since it offers this nice snippets feature.
Here's the code, I placed at the end of node.tpl.php (for version 4.7):
<?php if ($page != 0) { $words = search_index_split($node->title); $searchArgs = ""; foreach($words as $word) { if (strlen($word) > variable_get('remove_short', 3)) { if (!empty($searchArgs)) { $searchArgs .= " OR "; } $searchArgs .= $word . " "; } } if (strlen($searchArgs) > 0) { $results = node_search('search', $searchArgs); if (is_array($results) && count($results) > 0) { print '<hr />'; print '<div id="related_nodes">'; print '<h2>The following articles may be of interest to you, too:</h2>'; $list = array(); $count = 0; foreach($results as $item) { if ($item['title'] == $node->title) { continue; } $list[] = l($item['title'], ltrim($item['link'], '/')) . ": " . strip_tags($item["snippet"]); if (++$count > 4) { break; } } print theme("item_list", $list); print "</div>"; } } } ?>
This is the code for Drupal 4.6:
<?php if ($page != 0) { $words = search_keywords_split($node->title); $searchArgs = ""; foreach($words as $word) { if (strlen($word) > variable_get('remove_short', 3)) { $searchArgs .= $word . " "; } } if (count($searchArgs) > 0) { $results = node_search("search", $searchArgs); if (is_array($results) && count($results) > 0) { print '<hr />'; print '<div id="related_nodes">'; print '<h2>The following articles may be of interest to you, too:</h2>'; $list = array(); $count = 0; foreach($results as $item) { if ($item['title'] == $node->title) { continue; } $list[] = l($item['title'], $item['link']) . ": " . strip_tags($item["snippet"]); if (++$count > 4) { break; } } print theme("item_list", $list); print "</div>"; } } } ?>
Update: Now using search_keywords_split() rather than just explode() to extract keywords out of title.
Update September 10th, 2006: code for Drupal 4.7 added.
Comment by Marco
December 20, 2005 - 13:34
Neat! Definitely a feature I will implement on my website.
Thanks!