Categories
Drupal Development Resources

Drupal Related Posts Blocks in Drupal 7

This is an update to my original post for related posts blocks in Drupal 6.

Created a block of links for related posts is a useful way to keep visitors engaged in your website and continue reading. This method is specifically for showing other nodes with the same taxonomy terms, but it can be modified for other fields.

Requirements:

  1. Drupal 7+
  2. Views 3+
  3. Some PHP experience

A note about taxonomy terms in Drupal 7:

Drupal 7 stores taxonomy terms as a field. In my example, I have a field name called “Topics” for my blog entries with the machine name “field_topics”. You’ll need to change “field_topics” with your own field name.

Create a Block and Add Contextual Filters

Content: Has taxonomy term ID

  1. When the filter value is NOT available: Provide default value: PHP Code
  2. PHP Contexual Filter Code:
    field_topics)) { 
    	foreach($node->field_topics['und'] as $term) {
    		 $terms[] = $term['tid'];
    	}
    	return implode('+', $terms); 
    } else { 
    	return; 
    }
    ?>
    

    Make sure you change field_topics with your own field name.

  3. Check “Reduce Duplicates”
  4. Under “More”, check “Allow multiple values”.

Exclude the current node

  1. Add another filter for “Content: Nid”
  2. When the filter value is NOT available: Provide default value
  3. Type: Raw value from URL
  4. Path Component: 2
  5. Under “More”, check “Exclude”

Save your changes. Place your block anywhere on the node

Go celebrate.

6 replies on “Drupal Related Posts Blocks in Drupal 7”

Excellent post, just what I needed.

Just one question, Is there a way to limit how many related posts are shown?

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.