Overriding Theme Templates in Drupal 7

Last updated on
16 September 2016

Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites

Adding additional preprocess functions inside existing preprocess functions

You may want to add additional preprocess functions inside your theme's preprocess function or preprocess_hook function to create different variable in different situations. For instance, if you wanted to have a node-type template (node-story.tpl.php) you could create a function called MYTHEME_preprocess_node_story(), where you would set story specific variables. The title of the function is not called through the theme API, so you could call it whatever you like, but this would allow you to setup your own API for calling all node-type templates with only a few lines of code.

Drupal 7

function THEME_preprocess_node(&$variables) {
  $node = $variables['node'];

  // Create preprocess functions per content type.
  $function = __FUNCTION__ . '_' . $node->type;
    if (function_exists($function)) { 
      $function($variables);
    } 
}

You can then have a preprocess function depending per content type in your template.php like so:

function THEME_preprocess_node_MY_CONTENT_TYPE(& $variables) {
  // Code that is specific to this content type
} 

Help improve this page

Page status: No known problems

You can: