WordPress: open external links in a new window

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:

Essentially, this snippet of code identifies all external links by:

  1. selecting all the anchor tags in the document
  2. removing all links that don’t begin with http, https or ftp, as they are assumed to be relative links
  3. removing all links that, while absolute, point to the same domain

Once the external links are identified, the target attribute is set to _blank.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.