Tips, tricks, articles, rankings for Drupal developers

Overwrite the page title with preprocess_page function of Drupal

ballester's picture
ballester | Wed, 14/05/2014 - 19:35

The preprocess_page function allows us to override the title of any Drupal page (I'm not talking about the title tag, I'm talking about the <h1 id="page-title" class="title">. Remember that the Page Title <title> we can overwrite and parameterize by modules like Metatag module or Page Title module.

With the function preprocess_page we can access the variable $vars['title'] and change its value. This allows us for example concatenating text before or after the title or evaluating the content and modify it completely using PHP.

This time we will recover the value of the variable $vars['title'] that contains the title, then web will add a static text before and finally overwrite back the value of the variable $vars['title']. Also evaluate the node so that only affects node pages of a particular content type.

This is the sample code that will overwrite the title page of Drupal, you have to locate within the template.php file of the active theme Drupal website.

function YOUR_THEME_NAME_preprocess_page(&$vars) {
  $node = menu_get_object();
  if (isset($node->nid) && $node->type == 'your-content-type-name') {
    $custom_title= "My custom title on node: ". $node->title;
    $vars['title'] = $custom_title;

From here everyone can find useful, for example, I see it very useful to improve our architecture page and improve SEO. We can for example enhance the prominence of our <h1> overwriting titles with keywords to the title of a node or a landing page taxonomy term.

In a next trick we will try to use Drupal tokens or variables to improve the chances.

Average: 5 (1 vote)
Drupal version: 
Drupal skill: 
PHP, Drupal API


bill's picture
Submitted by bill (not verified) on
Your rating: 5

Anónimo's picture
Submitted by Anónimo (not verified) on
Your rating: 5
Thank you, it was very useful. Finally it worked!!!