How to add meta tags programmatically to custom pages in Drupal

| | 1 min read

Meta tags are used for page description, ever wondered on how to add meta tags for the custom pages in Drupal 7. Using hook_html_head_alter() or using hook_preprocess_html() we could add Meta tags and title.

Sample code for adding meta tag description in a page use anyone of the below code in MYTHEME/template.php.


function MYTHEME_html_head_alter(&$head_elements) {
  $head_elements['metatag_description'] = array(
      '#theme' => 'metatag',
      '#tag' => 'meta',
      '#id' => 'metatag_description',
      '#name' => 'description',
      '#value' => 'Description for meta-tags',
      '#type' => 'html_tag',
    );
}

Or you can use the folowing code for achieving the same goal


function MYTHEME_preprocess_html(&$vars) {
  $metatag_description = array(
      '#type' => 'html_tag',
      '#tag' => 'meta',
      '#attributes' => array(
        'name' => 'description',
        'content' => 'Description for meta-tags',
      )
    );
    drupal_add_html_head($metatag_description, 'description');
}