Override how a Drupal Page is Displayed Based on Content Type

Posted By Alex Fisher on Friday, May 21, 2010 - 08:39

Have you ever wanted to change the way Drupal displays pages for certain content types? Drupal has built-in functionality that allows you to add additional template files to your Drupal themes. However, as of Drupal 6, it will not allow you to override page.tpl.php based on content type. You change this by adding a small amount of code to your Theme's template.php file:

  1. function THEMENAME_preprocess_page(&$vars, $hook) {
  2.   $template_files = array();
  3.   foreach ($vars['template_files'] as $file) {
  4.     $template_files[] = $file;
  5.     if ($file == 'page-node') {
  6.       $template_files[] = 'page-'. $vars['node']->type;
  7.     }
  8.   }
  9.   $vars['template_files'] = $template_files;
  10. }

After adding this code, you'll be able to create a separate copy of page.tpl.php and modify it for specific content types.

For example, if you have a content type called "Landing Page" you could make a copy of page.tpl.php called page-landing_page.tpl.php and change it to display Landing Pages differently. It's important to note, the name of the file depends on the machine readable name for the content type. Typically, this name is the same as the human readable name except all characters are lowercase and spaces are replaced by underscores.