Smartphone Touch Icon for a Drupal 7 Site

I recently had the need to create an image so that when a user bookmarks a site on their smartphone and adds that bookmark to their home screen, an icon appears. Scott Sawyer has an excellent post detailing the setup to add this image to your Drupal 7 site. I recommend checking it out.

One issue that I ran into was that the path to the icon was different between my local development environment and the site's live environment. A single, absolute URL to the image wouldn't work consistently between the two environments.

Enter base_path() and path_to_theme().

base_path()

base_path() returns the absolute directory to the root of your site, regardless if the site is in a subfolder or not. Check out the examples on the API page. Since my local environment was in a subfolder, and my live environment was at the site root, this function solves my problem.

path_to_theme()

Sure, we could stop with base_path() by writing the path from the Drupal root directory down to the image. However, path_to_theme() does a lot of that work for us. This function returns the path to the active theme.

The Setup

I've created an "images" folder in my theme, and I placed the icon image there. Therefore, base_path().path_to_theme().'/images/icon.png'  will return the path to the image for both my local development site and the live site.

The Code

With the code below in my theme's template.php file, I am now able to add the touch icon to my site.

    
      function THEME-NAME_preprocess_html(&$variables) {  // replace THEME-NAME with your theme
$appleIcon = array('#tag' => 'link', '#attributes' => array('href' => base_path().path_to_theme(). '/images/apple-touch-icon.png', 'rel' => 'apple-touch-icon', 'type' => 'image/png'),);
drupal_add_html_head($appleIcon, 'apple-touch-icon');
}

Putting it all together.