Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Embedding a 'Related Content' block in your Drupal nodes

Parent Feed: 

Many of my favorite websites offer a nice little feature, immediately following the body of the page, that highlights 3-5 "possibly related" stories or blog posts. I wanted to do this on OSC and some other sites, but found that it's difficult to add regions inside of nodes—the closest I could get with the default theme/block behavior is to have it appear after comment section, which is too far down the page to be relevant.

I decided to use the Featured Content module to create my blocks, as it offers a good amount of customization as to what kind of algorithms it uses to find related nodes... performance considerations aside. There are other ways to go about creating lists of related nodes, but this was quick and easy.

Adapting a solution I found here, I created a simple function inside my template.php file that allowed me to print a block from inside my node.tpl.php template.

Inside template.php:

<?php
/**
 * Helper function for retrieving block code for insertion into templates.
 *
 * @see http://drupal.org/node/753516#comment-2769068
 */
function osc_block_retrieve($module, $delta) {
 
$block = (object) module_invoke($module, 'block', 'view', $delta);
 
$block->module = $module;
 
$block->delta = $delta;
  return
theme('block', $block);
}
?>

Inside node.tpl.php:

<?php
 
<?php if ($page): ?>

    <div class="block-in-node">
      <?php print osc_block_retrieve('featured_content', '1'); ?>
    </div>
  <?php endif; ?>
?>

I chose to rank related nodes first by similar taxonomy terms, then by how many views the node received (I'm using the statistics module on this site).

Alternatively, you could do one of the following to accomplish the same kind of thing:

  • Set up a region inside your nodes, in the node.tpl.php file. This seems to be a little burdensome, though, unless you're planning on doing many different things inside said region(s).
  • Use the Panels module to add blocks inside of nodes, or in a different kind of page layout.
Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web