Replace Drupal favicon

Sometimes, you want to get rid of the default Drupal favicon, and use the ICO and PNG versions from your own theme.

/**
 * Implements hook_html_head_alter().
 */
function MYTHEME_html_head_alter(&$head_elements) { 
  foreach ($head_elements as $key => $unused) {
    if (preg_match('/favicon\.ico$/', $key) === 1) {
      unset($head_elements[$key]);
    }
  }
}

/**
 * Implements template_preprocess_html().
 */
function MYTHEME_preprocess_html(&$variables) {
  $path = base_path() . path_to_theme();

  drupal_add_html_head(array(
    '#tag' => 'link',
    '#attributes' => array(
      'href' => $path . '/images/favicon.ico',
      'rel' => 'shortcut icon',
      'type' => 'image/vnd.microsoft.icon'
    ),
  ), 'favicon-ico');

  drupal_add_html_head(array(
    '#tag' => 'link',
    '#attributes' => array(
      'href' => $path . '/images/favicon.png',
      'rel' => 'icon',
      'type' => 'image/png'
    ),
  ), 'favicon-png');
}

Tags

drupal theming drupal 7