Many times there are links to internal and external sources within content. For a reader it’s not always clear if they’ll be taken to a different site or stay on the current site. Hovering over a link to check the left bottom corner matches the domain is simply a inconvenience. You and I can both agree that this isn’t giving the reader the best experience.

The best solution is to add a small icon. This makes it clear that a link is going to be directing the reader to a external site. Adding a icon manually every time is tedious and without a doubt will be forgotten or inconsistent throughout the site.

It is quick and easy to do this automatically, and will never be forgotten or inconsistent. It only requires a small code snippet and does not add any notable loading times to the page.

The code snippet below automatically adds the external-link icon to all anchors that are different from the host. The icon is added as a SVG at the top of the code snippet (taken from Dashicons), this can be replaced by any other SVG or image if desired.

The result is in this very blog post, the previous Dashicons link has the icon added through this code snippet.

The result with internal and external links

Jeroen Sormani

I'm a professional WordPress plugin developer on a mission to create the best plugins for my clients. I'm specialised in developing general WordPress, WooCommerce and Easy Digital Downloads plugins.

Interested in talking about a WordPress project? Get in touch!

Follow me on Twitter

5 thoughts on “Adding a Icon to External Links

Carsten June 25, 2022 at 7:35 am

Hi Jeroen,
Thank you for this contribution. I would like to know to what extent I have to change this PHP coder to include my own icon as svg.
for example: ******
Many Thanks

Jeroen Sormani June 28, 2022 at 10:29 am

Hi Carsten,

Sure, you can change the svg by changing the HTML tag in the var Icon = '<svg ....'; piece of the code.

Cheers,
Jeroen

David July 25, 2022 at 2:20 pm

Hi Jeroen,

This is a great piece of code, very helpful!

It does, however, include all links like ‘mailto:’ and ‘tel:’, so it adds icon to all email addresses and phone numbers etc.

Can you please advice how to modify to exclude these specific links?

Thanks a lot,
David

Jeroen Sormani July 27, 2022 at 11:22 am

Hi David,

If you want to check for something like that you can add additional checks in the if statement;

if (link.host !== window.location.host && link.href.substr(0,4)!='tel:' && link.href.substr(0,7)!='mailto:') {

Cheers,
Jeroen

David July 29, 2022 at 8:56 am

This is stunning Jeroen!

Thanks a lot!!

Cheers,
David

Leave a Reply