Skip to content

Instantly share code, notes, and snippets.

@morgyface
Created July 9, 2019 14:13
Show Gist options
  • Select an option

  • Save morgyface/bebcdd8cb94949c50305853559ab11a8 to your computer and use it in GitHub Desktop.

Select an option

Save morgyface/bebcdd8cb94949c50305853559ab11a8 to your computer and use it in GitHub Desktop.
WordPress | Favicon and tile color function
<?php
function list_favicons($favicon_folder, $tile_color = null) {
/**
* Looks in the theme's favicon folder for ico and png files, if files exist
* a list of favicons will be generated within <head>
*
* To cover most devices, copy four files into the folder:
* A standard favicon.ico which is a compilation of three PNG's 16, 32 and 48.
* Two Apple device favicons: favicon-152.png and favicon-120.png
* A Microsoft favicon: favicon-144.png
* All icons should be square, i.e. have a height equalling the width.
*
* You can also pass in a colour for the Microsoft tile.
*/
$favicon_folder .= '/';
$favicon_directory = wp_normalize_path( get_template_directory() . '/' . $favicon_folder );
$favicons = glob( $favicon_directory . '*.{ico,png}', GLOB_BRACE );
if( $favicons ) {
$output = '';
foreach( $favicons as $favicon ) {
$path_parts = pathinfo( $favicon );
$favicon_ext = $path_parts['extension'];
if( $favicon_ext == 'ico' ) {
$rel = 'shortcut icon';
$sizes = null;
} else {
$dimensions = getimagesize($favicon);
$favicon_width = $dimensions[0];
if ( $favicon_width == '152' || $favicon_width == '120' ) {
$rel = 'apple-touch-icon-precomposed';
$sizes = 'sizes="' . $favicon_width . 'x' . $favicon_width . '"';
} elseif ( $favicon_width == '144' ) {
$name = 'msapplication-TileImage';
$rel = null;
}
}
$favicon = get_theme_file_uri( $favicon_folder . basename( $favicon ) );
if( $rel ) {
$output .= '<link rel="' . $rel . '" ';
if( $sizes ) {
$output .= $sizes . ' ';
}
$output .= 'href="' . $favicon . '" />';
} else {
$output .= '<meta name="' . $name . '" content="' . $favicon . '">';
}
$output .= PHP_EOL;
}
if( $tile_color ) {
$output .= '<meta name="msapplication-TileColor" content="'. $tile_color . '">' . PHP_EOL;
}
return $output;
}
}
@morgyface
Copy link
Author

morgyface commented Jul 9, 2019

Favicon and tile color function

A slight variation on this gist which injects the list directly into the <head>.

This is less intrusive, in that you can manually add it to the header include.

Used like this <?php echo list_favicons('favicon', '#111111');?>

This function works best with the following range of favicon files:

  • favicon.ico - A compilation of 3 or 4 images. Typically 16 × 16, 32 × 32 and 48 × 48. Some like to include 96 × 96 also.
  • Two favicon files for Apple devices - favicon-120.png and favicon-152.png
  • A favicon file for Microsoft devices - favicon-144.png

I use this online tool to generate my .ico file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment