How to override page.tpl.php in Drupal 7

May 20, 2011 7:46 pm Published by 9 Comments

It’s a fairly common requirement to override the default page template (page.tpl.php) based on the content type within Drupal, but it took me a little while to figure out how to do this in Drupal 7. The solution is actually very straight-forward so I thought I would share.

First paste the following code into your template.php file (if you haven’t already got one just create a file named template.php in your theme folder):

function yourthemename_preprocess_page(&$vars) {
if (isset($vars['node']->type)) {
$nodetype = $vars['node']->type;
$vars['theme_hook_suggestions'][] = 'page__' . $nodetype;
}

Replace the text yourthemename with the name of your theme. Now create a file in your theme folder containing the name of your content type e.g:

page–content_type.tpl.php

Replace content_type with the name of the content type you set up – check this matches the machine readable name in the admin section by going to ‘structure > content types’. You will see a list of the content types on your site with the ‘machine name’ next to them.

Clear your cache and refresh your page – you should now be able to customise your page template based on content type!

If this doesn’t work for you here’s a quick list of troubleshooting tips to prevent you from pulling your hair out:

  • Make sure your new ‘page–content_type.tpl.php’ is different to the default ‘page.tpl.php’ (otherwise it may well be overriding, but you won’t see any difference!)
  • Ensure you have cleared your cache
  • Ensure your theme has a page.tpl.php

 

Categorised in:

This post was written by WillyNilly

9 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *