Dynamic Favicons for WordPress

No Comments

Usually, a single favicon is used throughout a complete area. However there are occasions you wanna step it up with totally different favicons relying on context. A web site would possibly change the favicon to match the content material being seen. Or a website would possibly enable customers to personalize their theme colours, and people preferences are mirrored within the favicon. Possibly you’ve seen favicons that try and alert the consumer of some occasion.

A number of favicons can technically be managed by hand — Chris has proven us how he makes use of two totally different favicons for improvement and manufacturing. However while you attain the dimensions of dozens or a whole bunch of variations, it’s time to dynamically generate them.

This was the scenario I encountered on a latest WordPress venture for a listing of schools and universities. (I beforehand wrote about querying close by places for a similar venture.) When viewing a faculty’s profile, we needed the favicon to make use of a faculty’s colours relatively than our default blue, to present it that further contact.

With over 200 faculties within the listing and climbing, we would have liked to go dynamic. Thankfully, we already had customized meta fields storing information on every college’s visible identification. This included college colours, which had been getting used within the stylesheet. We simply wanted a solution to apply these customized meta colours to a dynamic favicon.

On this article, I’ll stroll you thru our strategy and a few issues to be careful for. You possibly can see the leads to motion by viewing totally different faculties.

Every favicon is a distinct coloration within the tabs based mostly on the college that’s chosen.

SVG is essential

Due to improved browser assist for SVG favicons, implementing dynamic favicons is far simpler than days previous. In distinction to PNG (or the antiquated ICO format), SVG depends on markup to outline vector shapes. This makes them light-weight, scaleable, and better of all, receptive to every kind of enjoyable.

Step one is to create your favicon in SVG format. It doesn’t harm to additionally run it by way of an SVG optimizer to eliminate the cruft afterwards. That is what we used within the college listing:

CodePen Embed Fallback

Hooking into WordPress

Subsequent, we wish to add the favicon hyperlink markup within the HTML head. How to do that is completely as much as you. Within the case of WordPress, it might be added it to the header template of a kid theme or echo’d by way of a wp_head() motion.

perform ca_favicon() {
if ( is_singular( ‘college’ ) ) {
$post_id = get_the_ID();
$coloration = get_post_meta( $post_id, ‘coloration’, true );

if ( isset( $coloration ) ) {
$coloration = ltrim( $coloration, ‘#’ ); // take away the hash
echo ‘<hyperlink rel=”icon” href=”‘ . plugins_url( ‘pictures/favicon.php?coloration=’ . $coloration, __FILE__ ) . ‘” sort=”picture/svg+xml” sizes=”any”>’;
}
}
}
add_filter( ‘wp_head’ , ‘ca_favicon’ );

Right here we’re checking that the submit sort is college, and grabbing the college’s coloration metadata we’ve beforehand saved utilizing get_post_meta(). If we do have a coloration, we move it into favicon.php by way of the question string.

From PHP to SVG

In a favicon.php file, we begin by setting the content material sort to SVG. Subsequent, we save the colour worth that’s been handed in, or use the default coloration if there isn’t one.

Then we echo the massive, multiline chunk of SVG markup utilizing PHP’s heredoc syntax (helpful for templating). Variables similar to $coloration are expanded when utilizing this syntax.

Lastly, we make a pair modifications to the SVG markup. First, courses are assigned to the color-changing parts. Second, a mode factor is added simply contained in the SVG factor, declaring the suitable CSS guidelines and echo-ing the $coloration.

As a substitute of a <type> factor, we might alternatively exchange the default coloration with $coloration wherever it seems if it’s not utilized in too many locations.

<?php
header( ‘Content material-Kind: picture/svg+xml’ );

$coloration = $_GET[ ‘color’ ] ?? ‘065281’;
$coloration = sanitize_hex_color_no_hash( $coloration );

echo <<<EOL
<svg xmlns=”http://www.w3.org/2000/svg” xmlns:xlink=”http://www.w3.org/1999/xlink” width=”1000″ peak=”1000″>
<type sort=”textual content/css”>
<![CDATA[
.primary {
fill: #$color;
}
.shield {
stroke: #$color;
}
]]>
</type>
<defs>
<path id=”a” d=”M0 34L318 0l316 34v417.196a97 97 0 01-14.433 50.909C483.553 722.702 382.697 833 317 833S150.447 722.702 14.433 502.105A97 97 0 010 451.196V34z”/>
</defs>
<g fill=”none” fill-rule=”evenodd”>
<g rework=”translate(183 65)”>
<masks id=”b” fill=”#fff”>
<use xlink:href=”#a”/>
</masks>
<use fill=”#FFF” xlink:href=”#a”/>
<path class=”major” masks=”url(#b)” d=”M317-37h317v871H317z”/>
<path class=”major” masks=”url(#b)” d=”M0 480l317 30 317-30v157l-317-90L0 517z”/>
<path fill=”#FFF” masks=”url(#b)” d=”M317 510l317-30v37l-317 30z”/>
</g>
<g fill-rule=”nonzero”>
<path class=”major” d=”M358.2 455.2c11.9 0 22.633-.992 32.2-2.975 9.567-1.983 18.375-4.9 26.425-8.75 8.05-3.85 15.458-8.458 22.225-13.825 6.767-5.367 13.3-11.433 19.6-18.2l-34.3-34.65c-9.567 8.867-19.192 15.867-28.875 21-9.683 5.133-21.525 7.7-35.525 7.7-10.5 0-20.125-2.042-28.875-6.125s-16.217-9.625-22.4-16.625-11.025-15.167-14.525-24.5-5.25-19.25-5.25-29.75v-.7c0-10.5 1.75-20.358 5.25-29.575 3.5-9.217 8.4-17.325 14.7-24.325 6.3-7 13.825-12.483 22.575-16.45 8.75-3.967 18.258-5.95 28.525-5.95 12.367 0 23.508 2.45 33.425 7.35 9.917 4.9 19.658 11.667 29.225 20.3l34.3-39.55a144.285 144.285 0 00-18.2-15.4c-6.533-4.667-13.65-8.633-21.35-11.9-7.7-3.267-16.275-5.833-25.725-7.7-9.45-1.867-19.892-2.8-31.325-2.8-18.9 0-36.167 3.325-51.8 9.975-15.633 6.65-29.05 15.75-40.25 27.3s-19.95 24.967-26.25 40.25c-6.3 15.283-9.45 31.675-9.45 49.175v.7c0 17.5 3.15 33.95 9.45 49.35 6.3 15.4 15.05 28.758 26.25 40.075 11.2 11.317 24.5 20.242 39.9 26.775 15.4 6.533 32.083 9.8 50.05 9.8z”/>
<path fill=”#FFF” d=”M582.35 451l22.4-54.95h103.6l22.4 54.95h56.35l-105-246.75h-49.7L527.4 451h54.95zM689.1 348.45H624L656.55 269l32.55 79.45z”/>
</g>
<path class=”protect” stroke-width=”30″ d=”M183 99l318-34 316 34v417.196a97 97 0 01-14.433 50.909C666.553 787.702 565.697 898 500 898S333.447 787.702 197.433 567.105A97 97 0 01183 516.196V99h0z”/>
</g>
</svg>
EOL;
?>

With that, you’ve received a dynamic favicon working in your website.

Safety issues

After all, blindly echo-ing URL parameters opens you as much as hacks. To mitigate these, we should always sanitize all of our inputs.

On this case, we‘re solely keen on values that match the 3-digit or 6-digit hex coloration format. We will embody a perform like WordPress’s personal sanitize_hex_color_no_hash() to make sure solely colours are handed in.

perform sanitize_hex_color( $coloration ) {
if ( ” === $coloration ) {
return ”;
}

// 3 or 6 hex digits, or the empty string.
if ( preg_match( ‘|^#([A-Fa-f0-9]{3}){1,2}$|’, $coloration ) ) {
return $coloration;
}
}

perform sanitize_hex_color_no_hash( $coloration ) {
$coloration = ltrim( $coloration, ‘#’ );

if ( ” === $coloration ) {
return ”;
}

return sanitize_hex_color( ‘#’ . $coloration ) ? $coloration : null;
}

You’ll wish to add your personal checks based mostly on the values you need handed in.

Caching for higher efficiency

Browsers cache SVGs, however this profit is misplaced for PHP recordsdata by default. This implies every time the favicon is loaded, your server’s being hit.

To cut back server pressure and enhance efficiency, it’s important that you just explicitly cache this file. You possibly can configure your server, arrange a web page rule by way of your CDN, or add a cache management header to the very prime of favicon.php like so:

header( ‘Cache-Management: public, max-age=604800’ ); // 604,800 seconds or 1 week

In our checks, with no caching, our 1.5 KB SVG file took about 300 milliseconds to course of on the primary load, and about 100 milliseconds on subsequent hundreds. That’s fairly awful. However with caching, we introduced this right down to 25 ms from CDN on first load, and 1 ms from browser cache on later hundreds — nearly as good as a plain outdated SVG.

Browser assist

If we had been accomplished there, this wouldn’t be internet improvement. We nonetheless have to speak browser assist.

As talked about earlier than, trendy browser assist for SVG favicons is stable, and fully-supported in present variations of Chrome, Firefox, and Edge.

SVG favicons have arrived… besides in Safari.

One caveat is that Firefox requires the attribute sort=”picture/svg+xml” within the favicon declaration for it to work. The opposite browsers are extra forgiving, however it‘s simply good follow. It’s best to embody sizes=”any” when you’re at it.

<hyperlink rel=”icon” href=”path/to/favicon.svg” sort=”picture/svg+xml” sizes=”any”>

Safari

Safari doesn‘t assist SVG favicons as of but, exterior of the masks icon characteristic meant for pinned tabs. In my experimentation, this was buggy and inconsistent. It didn’t deal with complicated shapes or colours effectively, and cached the identical icon throughout the entire area. Finally we determined to not hassle and simply use a fallback with the default blue fill till Safari improves assist.

Fallbacks

As stable as SVG favicon assist is, it‘s nonetheless not 100%. So you’ll want to add fallbacks. We will set an extra favicon for when SVG icons aren’t supported with the rel=”various icon” attribute:

<hyperlink rel=”icon” href=”path/to/favicon.svg” sort=”picture/svg+xml” sizes=”any”>
<hyperlink rel=”alternate icon” href=”path/to/favicon.png” sort=”picture/png”>

To make the positioning much more bulletproof, it’s also possible to drop the everlasting favicon.ico in your root.

Going additional

We took a comparatively easy favicon and swapped one coloration for one more. However taking this dynamic strategy opens the door to a lot extra: modifying a number of colours, different properties like place, totally totally different shapes, and animations.

As an illustration, right here’s a demo I’ve dubbed Favicoin. It plots cryptocurrency costs within the favicon as a sparkline.

Implementing dynamic favicons like this isn’t restricted to WordPress or PHP; no matter your stack, the identical rules apply. Heck, you would even obtain this client-side with information URLs and JavaScript… not that I like to recommend it for manufacturing.

However one factor‘s for certain: we’re certain to see inventive purposes of SVG favicons sooner or later. Have you ever seen or created your personal dynamic favicons? Do you’ve gotten any suggestions or tips to share?

The submit Dynamic Favicons for WordPress appeared first on CSS-Tips.

You possibly can assist CSS-Tips by being an MVP Supporter.

    About Marketing Solution Australia

    We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.

    Request a free quote

    We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.

    Subscribe to our newsletter!

    More from our blog

    See all posts

    Leave a Comment