Categories
Drupal Development Resources

Drupal Related Posts Blocks

Update: Drupal 7 version here

We needed a way to show a “related posts” block on our blog entries based on the topics assigned to the post. In Drupal, it can be accomplished by creating a Views block and placing it on the desired pages. In our case, we have a taxonomy vocabulary called “Topics” and I want them to show at the bottom of all blog entries.

Requirements:

  • Drupal 6+
  • Views 2+

Here’s how we did it:

Create the views block

The important part of this view is the “arguments” section. Everything else will be specific to your own Drupal site.

Add an argument for “Term ID”

This is how we tell the view to restrict the list of nodes to the ones with the same term(s) as the current post.

  • Under “Action to take if argument is not present”, check “Provide default argument”
  • In the “Provide default argument options” fieldset, check “PHP Code”
  • Copy and paste the following code into “PHP Argument Code”
  1. $node = node_load(arg(1));
  2. if($node->taxonomy) {
  3. foreach($node->taxonomy as $term) {
  4. $terms[] = $term->tid;
  5. } return implode(‘+’, $terms);
  6. } else {
  7. return;
  8. }
  • If you tag your nodes with more than one term, you’ll want to check “Allow multiple terms per argument” and “Reduce duplicates”

Don’t show the current node

Of course it would be unnecessary to include the current node as part of the “Related Posts” block. We can exclude the current node by adding a second argument for “Node: Nid”.

 

  • Under “Action to take if argument is not present”, check “Provide default argument”
  • In the “Provide default argument options” fieldset, check “Node ID from URL”
  • Check “Exclude the argument”

Place the block

Just place the block in the desired region of your theme. We prefer using the contexts module to the handle the blocks.

 

That’s it. With some basic Drupal Views skills, a little PHP, and a block, you can generate a related posts block based on the taxonomy.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.