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.
An Icon for External Links
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.
9 thoughts on “Adding a Icon to External Links”
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
Hi Carsten,
Sure, you can change the svg by changing the HTML tag in the
var Icon = '<svg ....';
piece of the code.Cheers,
Jeroen
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
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
This is stunning Jeroen!
Thanks a lot!!
Cheers,
David
Is amazing!
Thanks Jeroen.
Hi,
thank you very much for this very helpful snippet.
best regards
does this code stil work on WordPress installs today?
whilst it’s the sleekest most lightweight solution documented, for some, unknown reason and after lot’s of testing, this code fails to style the external links for content in a widgetised sidebar.
I’m not a programmer but chrome tools inspection of the item shows the test links are distinguished the same as a test set of link in the body of the page where they do display the external link icon, so there is data-type=”page” and data-type=”link”
Any ideas?
Hi Paul,
The snippet is designed to only look at the page content, so it doesn’t do the sidebar. If you’d also like to do that you’ll need to modify the snippet to include that within the query selector.
Cheers,
Jeroen