When I write my posts in WordPress, I sometimes forget to set target="_blank"
for the links I want to open in a new tab (or window, depending on the browser’s configuration). I could go back and edit my posts in WordPress, but it would be a tedious process. Since I want only external links to open in a new tab, I decided to add jQuery to select all links pointing to external sites and then set the target attribute automatically. I modified the header.php file for my WordPress theme to do just that:
1 2 3 4 5 6 7 8 9 10 |
$(document).ready(function() { $('a') .filter(function(){ return ($(this).attr('href').match(new RegExp('^https?|ftp'))); }) .filter(function(){ return (! $(this).attr('href').match(new RegExp('^(https?|ftp):\/\/'+location.hostname))); }) .attr('target', '_blank'); }); |
Essentially, this snippet of code identifies all external links by:
- selecting all the anchor tags in the document
- removing all links that don’t begin with
http
,https
orftp
, as they are assumed to be relative links - removing all links that, while absolute, point to the same domain
Once the external links are identified, the target
attribute is set to _blank
.