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.
Tags


Neat! Definitely a feature I will implement on my website.
Thanks!
Sweet. I implemented it here: http://www.enrichr.com/
Took 2 second to install, 5 to customize for a grand total of 7 seconds :) Nice work.
This snippet also displays comments as related nodes :(
How do I fix this?
Regards,
JR
wait, I just messed up my template wich put comments right below the Related: text.
doh
Wonderful. A great hack. Thanks.
Really a nice hack. I was in search of this feature for my website http://100rupees.com finally I got success in its implementation.
well though a nice hack, the same 5 links are being shown on all he pages of my site? What is causing this and How to overcome this problem ?
I think this only works for NODE content type and not for others !
@ Previous poster - You are editing the main template which gets included in all pages. Try to make a block and than put the php code in it.