Show taxonomy terms Grouped By Taxonomy Parent

Lately I was assigned with the task to display all terms assigned to a node, grouped by their parent. To better explain this, let's say for example that we have the Vocabulary 1 assigned to Content Type A, with the following terms:
 
Parent 1
-- term 1
-- term 2
-- term 3
Parent 2
-- term 4
-- term 5
Parent 3
-- term 6
-- term 7
etc. 
 
Nodes from Content Type 1 have various terms assigned. For example, node/143 has the following terms assigned: term 2, term 4, and terms 6 & 7.
 
The requirement was to display the node like this:
 
Node Title
Node Content
Parent 1
-- term 2
Parent 2
-- term 4
Parent 3
-- term 6
-- term 7
 
In order to achieve the above, I created a View (Node). In this View, I added a relationship of Parent Term. Then, in the fields, I added Taxonomy: Term, select the Parent Term relationship, and excluded it from display. (This would be the Parent label). Then, I once again added the field Taxonomy: Term. (This would be the terms). This would display the Parent of each term as well, like Parent 1: term 1. Sweet.
 
So now for the groupping part:
 
In the Style option (under the basic settings), by little gear icon, I selected the Group By: Taxonomy: Term (The field that holds the relationship). You can select any format you would like, as long as you adjust the groupping options accordignly. 
 
*If the groupping is not working as expected, make sure to disable the Themer module, as it messes with the output.* 
 
The view is ready and works like a charm :) All that's left, is to attach it to the node. There are many ways to do this, including a number of modules, but I preffered to do it with some code.
 
I copied the node.tpl.php and renamed it to node-content-type-1.tpl.php, to override the output of the node for this particular content type. I deleted the section where terms are printed, and programmatically inserted the view, with the node id argument, using:
 
<?php
$viewName = 'views_name';
$display_id = 'default';
print views_embed_view($viewName, $display_id, $node->nid);
?>
 
And that's it :) The terms of the nodes are displayed under each node, and groupped by the term parent. 
 

Tags: 
Drupal 6, Drupal theming, Drupal Quick Tips, Taxonomy

Recent Comments

Forward by Dries Buytaert, Founder and Project Lead, Drupal; CTO Acquia.

Order now from:

Managing Expectations Podcast with DrupalEasy

Author Interview http://tinyurl.com/8a8nxno

We provide the most Shiny Drupal Bits & Pixels

Since Drupal 4.x