Adding a favicon to your site (including at the root)

Adding a favicon is an important finishing touch to building your site. If your theme doesn’t support favicons, you can add a favicon by adding the following code to your functions.php :

add_action('wp_head', 'emw_add_favicon');

function emw_add_favicon () {
	echo '<link rel="shortcut icon" type="image/x-icon" href="'.get_stylesheet_directory_uri().'favicon.ico">'."\r\n";
	echo '<link rel="icon" type="image/x-icon" href="'.get_stylesheet_directory_uri().'favicon.ico">'."\r\n"; // Shouldn't be necessary, but added for maximum browser compatibility
}

If your theme already supports favicons, chances are there’s a filter in place so you can provide your own. For example, this is how to add a favicon to the Genesis theme:

add_filter ('genesis_pre_load_favicon', 'emw_add_genesis_favicon');

function emw_add_genesis_favicon ($text) {
	return get_stylesheet_directory_uri()."favicon.ico";
}

Or, if you prefer to keep your code ultra-compact:

add_filter ('genesis_pre_load_favicon', create_function ('', 'return get_stylesheet_directory_uri()."favicon.ico";'));

There’s one final problem to solve. Many browsers look for the favicon in your domain root: i.e. at www.domain.com/favicon.ico We could of course place the icon file there, but there’s no need to. A few lines of WordPress code will redirect browser requests to the right place:

add_filter('rewrite_rules_array', 'emw_favicon_rewrite');

function emw_favicon_rewrite($rewrite_rules) {
    $new_rules = array('favicon.ico' => get_stylesheet_directory_uri()."favicon.ico");
    $rewrite_rules = $new_rules + $rewrite_rules;
    return $rewrite_rules;
}

This function works by adding a favicon line to the array of rewrite rules, every time the array is updated. This means that you’ll need to force an update of all the rules before this extra rule will be added – and the easiest way to do that is to change your permalink structure, and then immediately change it back.