Recently I was working in a project where we needed to show page title in format of [ node count associated with taxonomy term] [taxonomy term page is associated with] | [site name]. By default drupal 7 provides page title “term name | site name” for term pages. Our requirement was to get page title 125 vegetable recipe blog | my site name. Here 125 is node count of vegetable recipe tag. This is how we have  achieved this using  hook_preprocess_html().

Let’s create module called custom_title & create function custom_title_preprocess_html as follows in custom_title.module file.

/**
 * Implements hook_preprocess_html().
 */
function custom_title_preprocess_html(&$variables) {
  // Make sure current page is taxonomy/term/tid
  // In case if you use alias then you can use these way
  // Let’s say your term page is vegetables/tomato then use like
  // if( arg(0) = 'vegetables' && count(arg()) == 2 ){
  // and alternatively change loading term from name to tid
  if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    //loading term by tid
    $term = taxonomy_term_load(arg(2));

    //get node count by replacing token value
    $term_node_count = token_replace('[term:node-count]', array('term' => $term));

    //get site name
    $site_name = token_replace('[site:name]');
    $head_title = $term_node_count . " " . $term->name." blogs | " . $site_name;

    //add title
    $variables['head_title'] = $head_title;
  }
}

Now just enable this module and clear your Drupal cache. You should see  your page title like “ 125 vegetable blogs | site name ”. 

Similar to above example you can change page title like “Page Title | Krishna blog” using hook_preprocess_html(). In this case Krishna is node author. Custom or dynamic page title for node pages:

/**
 * Implements hook_preprocess_html().
 */
function custom_title_preprocess_html(&$variables) {
  // Make sure current page is node/nid
  // It will even if use aliases.
  if(arg(0) == 'node' && is_numeric(arg(1)) && count(arg()) ==2){
    //load node from nid
    $node = node_load(arg(1));
    //load user from uid
    $user = user_load($node->uid);
    //add title
    $head_title = $node->title . " | " . $user->name . " blog";
    $variables['head_title'] = $head_title;
  }
}

The way we have customized node page title & term page titles, similarly we can use hook_preprocess_html() hook to customize other page titles like user pages, search page titles or any custom pages.

 

comments powered by Disqus