Easily Define preprocess functions by content type in Drupal

by John McGeechan


A shorthand way to provide preprocess "hooks" for any content type.

This snippet can be placed in a template or your chosen module, I usually place this in both the node and page preprocess function eg

function MYMODULE_preprocess_page (&$variables) {

$contentTypePreprocessor = "MYMODULE_preprocess_page_" . $variables['node']->type;

  if(function_exists($contentTypePreprocessor)) {



  ...do some more stuff


This simply checks for an existing preprocess function for the current content type and if one exists it is invoked and the variables array is passed through (as always pass by reference).
Then when I need to do some preprocess logic for a specific content type, I simply write the function in the module file. So for example if I have a content type of  "dogs"

function MYMODULE_preprocess_page_dogs (&$variables) {

  $variables['bone_appreciation'] = 'high';
  $variables['cat_appreciation']  = 'low';


Clearly the example above could be repeated for the node preprocess logic and could also have been placed directly in template.php