Page template suggestions for taxonomy vocabs

Drupal's template suggestions are plentiful and pretty powerful stuff, however, given all the options there are some noteable oversights. In particular the ability to use page-taxonomy suggestions per vocabulary, something like page-vocab-1.tpl.php to theme all taxonomy term pages in vocabulary 1 (where 1 is the VID or vocabulary id).

To achieve this we turn to our trusty preprocess_page function which by now every Drupal themer worth his or her salt knows all about.

The job is strait forward - grab the term from Drupals internal path, lookup its VID in the database, then use it to add new template suggestions. Simple eh? Yeah, I thought so to.

Template suggestions for every vocab

This snippet will allow you to create and use template suggestions for every vocab, so if you have more than one vocab you have a suggestion for each one. The template name will be in this form - page-vocab-[vid].tpl.php, if you have three vocabs and their VID are 1, 2 and 3 respectfully you could use suggestions as follow:

  • page-vocab-1.tpl.php
  • page-vocab-2.tpl.php
  • page-vocab-3.tpl.php

Heres the code, this goes in your themes template.php file or, more specifically in themeName_preprocess_page(), because some themes like Adaptivetheme and Studio place these functions in inc files.

Note that you don't have to build a template for every vocab, if the vocab specific tpl file does not exist Drupal will fall back and use page.tpl.php.

<?php
/**
* Override or insert variables into the page templates.
*
* @param $vars
*   An array of variables to pass to the theme template.
* @param $hook
*   The name of the template being rendered.
*/
function themeNAME_preprocess_page(&$vars) {
  if (
arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
   
$tid = arg(2);
   
$sql = "Select vid from {term_data} WHERE tid = '%d'";
   
$vid = db_result(db_query($sql, $tid));
   
$vars['template_file'] = 'page-vocab-' . $vid;
  }
}
?>

Template suggestion for just one vocabulary

OK, thats all well and good, but could be overkill for your case and perhaps you only want to tell Drupal to use a different template for one vocab, pretty easy also...

<?php
/**
* Override or insert variables into the page templates.
*
* @param $vars
*   An array of variables to pass to the theme template.
* @param $hook
*   The name of the template being rendered.
*/
function themeNAME_preprocess_page(&$vars) {
  if (
arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
   
$tid = arg(2);
   
$sql = "Select vid from {term_data} WHERE tid = '%d'";
   
$vid = db_result(db_query($sql, $tid));
    if (
in_array($vid, array('1'))) {   // where 1 is the vid
     
$vars['template_file'] = 'page-vocab-1';
    }
  }
}
?>

Last updated 29th November, 2009 - 10:15pm

Authored by Jeff Burnz on