30 Jul

External Link Favicons in WordPress

Many favicons from random websites

Favicons (aka “favourites icons”) are small icons, typically 16 x 16 pixels, that represent your website in browser tabs, bookmarks, desktop shortcuts and more. They’ve been around since 1999, are in use by most sites, we’ve all seen them.

We are soon adding a links and resources page to CodePeach for web development, coding and design sites that we find useful. A page full of text links never looks appealing, so I thought one way of spicing up a links page visually would be to place each link’s small favicon image next to the link itself. It’s also a great way for users to visually relate to the linked websites.

So let’s look at how to create a shortcode to display the favicon for a remote website in our WP content.

Fetching a Favicon

It is possible with PHP to try and grab a favicon file via it’s traditional URL ( /favicon.ico ), and if it’s found then save it to a folder.

If it’s not at that URL, then you can grab the webpage itself, and try and find it’s location by searching the returned page’s source for a shortcut icon / favicon link tag, which typically looks like one of the following:

Of course to grab remote files we would need to check if the PHP server our WP is on has curl installed or has permission for file_get_contents function, then deal with errors fetching the remote URL, checking we have write access to a cache folder, checking the retrieved file is a valid image and so on.

Wanting to keep this exercise simple, I looked into alternative options and discovered great API / services available to use which do the work of fetching it for us.

Favicon Fetching API: getFavicon

After experimenting with several Favicon fetching APIs available, I found one to be considerably more reliable than the others, and is open soruce: getFavicon by Jason Cartwright.

Visit: http://g.etfv.co/

Here’s an example of it’s usage:

Which gives us this image: CodePeach favicon grabbed from getFavicon API

Sweet.
Let’s make a WP shortcode to generate this.

WordPress Favicon Shortcode

If you’re new to coding your own WordPress shortcodes, you might want to check out our shortcode development beginner tutorial.

Let’s make it so the following shortcode will output an image tag for the favicon for the link src we specify, with an alt tag (if specified):

Let’s add some code to your theme’s functions.php file to add the shortcode and define it’s functionality:

Hope you find this useful :]
testing icon! testing icon! testing icon!

Related Posts

  • Grabicon

    g.etfv.co seems to be out of commission, but grabicon.com is also free, lets you specify image size, and generates a unique default icon for sites that don’t have one. I’m the creator, and I’m open to other features as well if people need them. Thanks!