Front-end engineer with a passion for learning something new every day

Creating Custom Content Type Page Templates with Drupal 6

We were recently asked to create custom landing pages for a Google ad campaign for a Drupal site we developed. The issue we faced was that the layout for the landing page was not really close to anything in the existing theme.

Drupal by default can do custom node type templates based off any given custom content type
(node-blog.tpl.php for example) but all that does is theme and customize the content area.
In our case we needed to change the entire page layout. Well it turns out there is a Drupal
PHP preprocess function that can help accomplish custom page templates.

For this to work you need to alter template.php in your Drupal site theme folder. If you don’t have this file yet, you can go ahead and create a blank one that you will add code to.

In your theme's template.php file add this code (Drupal 6):


/**
* Add / modify variables before the page renders.
*/

function phptemplate_preprocess_page(&$vars) {

// custom content type page template
  // Renders a new page template to the list of templates used if it exists
  if (isset($vars['node'])) {
    // This code looks for any page-custom_content_type.tpl.php page
    $vars['template_files'][] = 'page-'. str_replace('_', '-', $vars['node']->type);  
  }
}

In your theme's template.php file add this code (Drupal 7):


/**
* Add / modify variables before the page renders.
*/

function yourthemename_preprocess_page(&$vars) {
// custom content type page template
  // Renders a new page template to the list of templates used if it exists
  if (isset($vars['node']->type)) {
// This code looks for any page--custom_content_type.tpl.php page
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}

And here is how this works: Lets say you create a custom content type called "Landing" with a machine name of "landing'. You could duplicate your page.tpl.PHP, rename it to page-landing.tpl.php (Drupal 6), page--landing.tpl.php (Drupal 7 -- note the extra hyphen!) and then customize the entire layout of that page with CSS & HTML as per your specifications. Now when you have any pieces of content that are designated as Type "Landing" the new custom template you just made will be used automatically to render that content. Remember to clear your Drupal cache for this to work.

Tags

Read other blog posts