Make Node Fields Accessible in Page.tpl.php

Last modified: 
Wednesday, August 26th, 2015

Problem Description

  • We have a vocabulary for site section, which can be used to apply a single term to each node.
  • We want to label each node's site section in the branding area of page.tpl.php.
  • The template page.tpl.php contains information about the nodes within, but they are buried deep with the $variables['page'] array.
  • In our example, the field_site_section array is stored in the Title object of each node.
  • We are only concerned with nodes displayed as pages.

Solution

  • We update MYTHEME_preprocess_page() to check is we're displaying node.
  • If so, set a new $variables item $variables['page_site_title'] using a function _MYTHEME_get_site_section().
  • _MYTHEME_get_site_section() simply filters through all the noise in the $variable['page'] to find the site section tid, looks up the string value of for the term, and returns it.

In template.php (or equivalent)

/**
 * Implements hook_preprocess_page().
 */
function MYTHEME_preprocess_page(&$variables) {

  // Makes the site section term easier to access in page.tpl.php
  if (arg(0) == 'node') {
    $variables['page_site_section'] = _MYTHEME_get_site_section($variables);
  }

}

/**
 * This function returns the string value of the site section from the Page scope,
 * so it can be easily accessed in page.tpl.php.
 * @param $variables
 *
 */
function _MYTHEME_get_site_section(&$variables) {

  $oTitle = $variables['page']['content']['system_main']['nodes'][arg(1)]['title']['#object'];
  if (property_exists($oTitle, 'field_site_section')) {
    $tid = $oTitle->field_site_section[LANGUAGE_NONE][0]['tid'];
    // Get the name associated with this tid.
    $term = taxonomy_term_load($tid);
    $page_site_section = $term->name;
  }
  else {
    $page_site_section = "";
  }

  // We're returning here in an effort encourage devs to alter the
  // the $variables variable in MYTHEME_preprocess_page();
  return $page_site_section;

}


The operator of this site makes no claims, promises, or guarantees of the accuracy, completeness, originality, uniqueness, or even general adequacy of the contents herein and expressly disclaims liability for errors and omissions in the contents of this website.