background image
HomeRecent PostsDrupalSearchTagsRSSContactAboutAccount

Custom theming based on a node's taxonomy

Eric.London's picture

Here is how you can customize your theme (page.tpl.php) based on a node's taxonomy. First, I created a taxonomy vocabulary called "Page Layout" and assigned to terms to it: Wide and Narrow. I set the vocabulary's hierarchy to be disabled and multiple select is disabled. I then placed this code in my page.tpl.php, but can reside in node.tpl.php (or essentially anywhere that has access to the $node global).

<?php
$vocabName
= 'Page Layout';

// get vocabularies for this node
$vocabs = taxonomy_get_vocabularies($node->type);

// loop through vocablularies, look for vid that matches vocab name
foreach ($vocabs as $vocab) {
  if (
$vocab->name == $vocabName) {
   
$vid = $vocab->vid;
    break;
  }
}

// lookup terms for this node, by vocabularyID
$nodeTerms = taxonomy_node_get_terms_by_vocabulary($node->nid, $vid);

// loop through node terms
foreach ($nodeTerms as $nodeTerm) {
  if (
$nodeTerm->vid == $vid) {
   
$cssClass = $nodeTerm->name;
    break;
  }
}
?>

Then, I can use the $className variable in my layout and theming. For instance...

<?php
print "<div class='$cssClass' />";
?>

...or like this...

<?php
switch ($cssClass) {
  case
'Wide':
   
// ...code...
   
break;
  case
'Narrow':
   
// ...code...
   
break;
}
?>