How to override page.tpl.php in Drupal 7
May 20, 2011 7:46 pm9 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.phpReplace 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: Web Development
This post was written by WillyNilly
9 Comments
Watch out for the odd single quotation marks (�page__� should be ‘page__’) and the missing } at the end of the first code snippet.
Otherwise, thanks for this, helped me out.
Oh, I see that WordPress automatically transforms single quotes into “pretty” quotes.
Hey Niklas well spotted – I should get into the habit of wrapping snippets with code tags that way WordPress doesn’t interfere and the snippets can be copied and pasted!
Hi, I want to create separate tpl for my donation form. I have followed the same procedures what you shared. But it doesn’t works for me
The template should be called
'page--content-type.tpl.php'
or it will not work.ack, its filtering the hyphens!
THX Drupaler, “The template should be called ‘page–content-type.tpl.php’ “
* page–content-type.tpl.php
Unfortunately your suggestion does not work. 🙁