Drupal: Altering Page Title and or Title Tag

Sometimes you need to alter the title that appears on the page and or the title tag in Drupal 7. If you need to make them both the same, a call to drupal_set_title() from within a hook_preprocess_page() will do it.

<?php
/**
 * Implements hook_preprocess_page().
 */
function MYMODULE_OR_THEME_preprocess_page(&$variables) {
 
// Alter the title to on content type XYZ.
 
if (isset($variables['node']) && $variables['node']->type == "XYZ") {
   
// I am an XYX so alter the page $title and <title>.
   
$new_title = t('This is some new title.');
   
// This will set the page $title and the <title> tag.
   
drupal_set_title($new_title);
  }
}
?>

If you need to only alter the on page title but NOT the Title tag, then this will do it.

<?php
 
/**
 * Implements hook_preprocess_page().
 */
function MYMODULE_OR_THEME_preprocess_page(&$variables) {
 
// Alter only content type XYZ.
 
if (isset($variables['node']) && $variables['node']->type == "XYZ") {
   
// I am an XYX so alter the page $title.
   
$new_title = t('This is some new title.');
   
// This will just set the page $title.
   
$variables['title'] = $new_title;
  }
}
?>

If you need to alter them both but make them both different, then you have to call drupal_set_title() first and alter the onpage title after that.  Otherwise drupal_set_title will overwrite your change.

<?php
/**
 * Implements hook_preprocess_page().
 */
function MYMODULE_OR_THEME_preprocess_page(&$variables) {
 
// Alter only content type XYZ.
 
if (isset($variables['node']) && $variables['node']->type == "XYZ") {
   
// I am an XYX so alter the page $title and <title>.
   
$new_title = t('This is some new title.');
   
$new_title_version_b = t('This is some other title for the page variable.')
   
// This will set the page $title and the <title> tag.
   
drupal_set_title($new_title);
   
// This will just set the page $title.
   
$variables['title'] = $new_title_version_b;
  }
}
?>

These methods are preferable to altering the page.tpl