March 26, 2009

Quick way to add ‘related reading’ to a node page in Drupal

Filed under: Tips — Tags: — Webopius @ 7:55 am

There are Drupal modules available that will take your node and display a block containing other nodes that use similar taxonomy terms to the node you have displayed.

Although these are available, you may be interested to use a small snippet of code that does the same thing for you and you can include it within your node’s node.tpl template.

Related articles code

This code needs to be included within your theme’s node.tpl file. I know it’s not the usual Drupal way to embed php into the templates and if this is a problem, you could always move this code into a theme preprocessor to give the template a variable instead.


<?php if ($page) { ?>
    <div class="relatedreading">
    <h2>Related content</h2>
    <?php 
    $termids = array();	
    $terms = $node->taxonomy; 
    if ($terms) {
        foreach ($terms as $key => $value) { 
            if ($value->vid == 2) {
                $termids[] = $value->tid;
            } 
        }
    }
    $relatednodes = taxonomy_select_nodes($termids);
    print '<ul>';
    while ($data = db_fetch_object($relatednodes)) {
        if ($data->nid != $node->nid) {
            $node_url = url("node/$data->nid");
            print '<li><a href="'.$node_url.'" title="'.$data->title.'">'.$data->title.'</a></li>';
        }
    }
    print '</ul>';
?>
</div>
<?php } ?>

How the ‘related reading’ code works

The only thing you need to change above is the $value->vid == 2 line and set the ‘2’ to the value of the taxonomy vocabulary that you’d like to find matching nodes for.

If the node is being displayed in a page view (on its own), this code will create an array of all taxonomy terms for that node from a specific vocabulary.

Next, it will look for all other matching nodes with the same taxonomy terms (taxonomy_select_nodes will return only the first 10 matches if no ‘pager’ parameter is passed because it follows the model of an XML feed).

For each match, it renders a list result with the title and link to the node.

  • Tags