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

  • Niklas Brunberg says:

    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.

  • Niklas Brunberg says:

    Oh, I see that WordPress automatically transforms single quotes into “pretty” quotes.

  • admin says:

    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!

  • Sarfraz says:

    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

  • Drupaler Shift says:

    The template should be called 'page--content-type.tpl.php' or it will not work.

  • Drupaler Shift says:

    ack, its filtering the hyphens!

  • juju says:

    THX Drupaler, “The template should be called ‘page–content-type.tpl.php’ “

  • juju says:

    * page–content-type.tpl.php

  • Anony Mouse says:

    Unfortunately your suggestion does not work. 🙁

Leave a Reply

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