Drupal 7: How to override the page.tpl for specific content types?

A common override that is not included in the default list is the page.tpl.php override based on the content type being displayed. There is a node.tpl.php override based on the same condition which leads to confusion as to where the page override exists. On top of that, themes like Zen add this type of override to the Template Suggestions, which leads those using Zen to believe that this is part of the default list. Check the theme documentation to see if this override has been added to the Template Suggestions by the theme. If it hasn’t, you need to add it manually.

The process is straightforward. We can create additional Template Suggestions simply by adding them to the ‘theme_hook_suggestions array in our template.php file.

  1. Open the template.php file in your theme for editing.
  2. Look for a function called yourthemename_preprocess_page (replace the yourthemename with your theme’s name).
  3. If this function already exists, you will need to add the if statement to the end of the function just before the closing bracket. Otherwise you’ll need to create a new function to look like this:

function themeName_preprocess_page(&$vars, $hook) {
if (isset($vars['node'])) {
// If the node type is "blog_madness" the template suggestion will be "page--blog-madness.tpl.php".
$vars['theme_hook_suggestions'][] = 'page__'. $vars['node']->type;
}
}

Required modifications: themeName = the name of your theme; some themes with existing preprocess functions require you to modify the function. To add $hook or to modify $vars into $variables throughout the code of the function. In my case the following worked:

function themeName_preprocess_page(&$variables, $hook) {
if (isset($variables['node'])) {
// If the node type is "blog_madness" the template suggestion will be "page--blog-madness.tpl.php".
$variables['theme_hook_suggestions'][] = 'page__'. $variables['node']->type;
}
(...)
}

The template file needs to be named as follows: page--name-node-type.tpl.php. Please note the double dash. The name of the node type needs to be spelled exactly as the machine name of the content type. (Example: machine name = tips_and_tricks, template file = page--tips_and_tricks.tpl.php.

Drupal PHP
Taxonomy: 

Drupal themes to be compared