Set Dynamic Favicons in WordPress Without A Plugin

Dynamic favicons aren’t new. I’ve seen many great examples on the web before. And today, I’ll show you an example script that programmatically sets dynamic favicons in WordPress without JavaScript. The article caters to users familiar with SFTP and editing theme files in WordPress.

I use GeneratePress Elements to add my PHP hooks. And if you aren’t a GP user, open https://example.com/wp-admin/theme-editor.php, and the script to the header.php file.

In this scenario, the favicon images and site background colors are set randomly on each load. Here’s the code snippet I’m using on mp.mt.

<!--  Select a hex code -->
<?php
$items = Array('f5deb3','fab1a0','BDC581','9AECDB','CAD3C8', 'ffcccc');
$color = $items[array_rand($items)]
?>

<!-- Load dynamic favicons-->
<link rel="icon" href="https://mp.mt/icons/<?php echo $color;?>/favicon-32x32.png" sizes="32x32" />
<link rel="icon" href="https://mp.mt/icons/<?php echo $color;?>/android-chrome-192x192.png" sizes="192x192" />
<link rel="apple-touch-icon" href="https://mp.mt/icons/<?php echo $color;?>/apple-touch-icon.png" />
<meta name="msapplication-TileImage" content="https://mp.mt/icons/<?php echo $color;?>/android-chrome-192x192.png" />	

<!-- Set Dynamic background color -->
<style type="text/css">
:root {
     --global--background--color: #<?php echo $color;
     ?> !important;
}
 body, 
.site-header, 
.site-foooter, 
.site-info, 
.separate-containers .inside-article, 
.separate-containers .comments-area, 
.separate-containers .page-header, 
.one-container .container, 
.separate-containers .paging-navigation, 
.inside-page-header, .main-navigation, 
.main-navigation ul ul {
     background: var(--global--background--color);
}
</style>	

As you can comprehend from the snippet, a random hex code is chosen on load, which sets the favicons and background colors, respectively. And I’ve already generated a bunch of favicons and saved them within the https://mp.mt/icons/ folder.

The script injects HTML <link> sizes Attribute. So you needn’t set the Site Icon in WordPress Customizer.

Cover Photo by Harpal Singh on Unsplash

Written by MighilMighil is an indie musician and tinkerer with diverse work experience in technology and writing. He has had the privilege of serving in various capacities, encompassing generalist and specialist roles. He is currently based in Chengdu.

Newsletter

Opt-in to receive long-form essays in your inbox. Unsubscribe anytime. Follow me on 𝕏 if you like.

Powered by DigitalOcean, BunnyCDN, WordPress.