Code to Add a Favicon to Your WordPress Site and Dashboard

James Parsons by James Parsons Updated Jul 4th, 2024 2 Comments

Not sure why you'd want to use an entire WordPress plugin for this easy task! Here's a custom code that adds a favicon to the front of your site and to the backend dashboard as well.

What's cool is this also pulls the valid mime type from the extension automatically, which means it works with any favicon type: PNG, JPG, SVG, ICO, etc. All you need to do is upload your image and replace the example image URL with a link to your favicon, and this code does the rest.

Simply add this at the bottom of your theme's functions.php file (example: /wp-content/themes/your_theme_name/functions.php):

// Add favicon to the frontend and backend

// Replace with your actual favicon URL
$favicon_url = 'http://example.com/uploads/files/favicon.png'; 

// No need to edit below this line
function generate_favicon_html() {
    global $favicon_url;
    $favicon_html = '';
    $extension = pathinfo($favicon_url, PATHINFO_EXTENSION);
    $favicon_html .= '<link rel="icon" type="image/' . $extension . '" href="' . $favicon_url . '">';
    return $favicon_html;
}
function add_favicon() {
    echo generate_favicon_html();
}
add_action('wp_head', 'add_favicon');
function add_admin_favicon() {
    echo generate_favicon_html();
}
add_action('admin_head', 'add_admin_favicon');
?>

Remember to swap out that example favicon link with a link to your favicon image.

Related Code Snippets

Written by James Parsons

James Parsons is the founder and CEO of Content Powered, a premier content marketing agency that leverages nearly two decades of his experience in content marketing to drive business growth. Renowned for founding and scaling multi-million dollar eCommerce businesses through strategic content marketing, James has become a trusted voice in the industry, sharing his insights in Search Engine Watch, Search Engine Journal, Forbes, Entrepreneur, Inc, and other leading publications. His background encompasses key roles across various agencies, contributing to the content strategies of major brands like eBay and Expedia. James's expertise spans SEO, conversion rate optimization, and effective content strategies, making him a pivotal figure in the industry.