Code to Add a Favicon to Your WordPress Site and Dashboard

Updated 07/04/2024, Posted 07/04/2024 by James Parsons James Parsons 0 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

Hi, I'm James Parsons! I founded Content Powered, a content marketing agency where I partner with businesses to help them grow through strategic content. With nearly twenty years of SEO and content marketing experience, I've had the joy of helping companies connect with their audiences in meaningful ways. I started my journey by building and growing several successful eCommerce companies solely through content marketing, and I love to share what I've learned along the way. You'll find my thoughts and insights in publications like Search Engine Watch, Search Engine Journal, Forbes, Entrepreneur, and Inc, among others. I've been fortunate to work with wonderful clients ranging from growing businesses to Fortune 500 companies like eBay and Expedia, and helping them shape their content strategies. My focus is on creating optimized content that resonates and converts. I'd love to connect – the best way to contact me is by scheduling a call or by email.