Created
July 9, 2019 14:13
-
-
Save morgyface/bebcdd8cb94949c50305853559ab11a8 to your computer and use it in GitHub Desktop.
WordPress | Favicon and tile color function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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; | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
I use this online tool to generate my
.icofile.