No credit card. Takes under a minute.

Login
INSIGHTS10 MIN READ

Tiny script opens external links in new tab: easy

The-Fran

Published on April 22, 2016

Published on Wealthy Affiliate — a platform for building real online businesses with modern training and AI.

Open select external links in a new tab - with a bit of unobtrusive JavaScript.

Do you want to keep visitors on you WordPress site—even when they click open affiliate or reference links embedded in your posts? Or did the Wordpress 4.5 update delete the "target" attributes that you had manually embedded in links? (1)

If you need a quick, easy solution, I've written such a script—actually a choice of two, which are included at the base of this article. Next, we will 1) hear why I chose a script versus a plugin; 2) enjoy undressing the external link; 3) rapidly zero in on how to use my tiny scripts to open external links for visitors in a new tab; and 4) determine which script will do exactly what you want.

If you are an advanced user; like the idea of a small script over a plugin, and know exactly how to add a script to a Text Widget and Footer; skip to the last section for the scripts.

plugin vs. my tiny script

Some plugins are absolutely essential for business, are multi-functional, and thus are probably "keepers". But having many plugins can slow the loading time of your pages, cost precious visitors, and increases "bounce rate" (2). So, it definitely pays to look at alternatives to plugins that have a single, simple purpose.

Conversely, a tiny script has the advantage of speed, flexibility, and no compatibility issues with plugins or themes. You can easily copy it from one site to another, and it's simple to paste into a Text widget (illustrated below) in the Footer—one time (and done).

As a bonus, my two little scripts never change your actual page or post code. If a link doesn't contain ' target="_blank" ', for example, it still won't. Instead, my script operates "live", only when someone visits your post or page. At that magical moment, it changes what their browser reads, virtually adding a "target" attribute to these links, causing a click to open the external site in a new tab or window, pursuant to your visitor's browser settings. It actually leaves your code as-is—completely in tact. (3)

Since all we need to do is add a simple attribute to links, we can do this dynamically "on the client", in a millisecond, with JavaScript. A plugin might be a bit overkill in this situation— kind of like going to the dentist to clean your teeth—every morning and between each meal. Ouch!

see external links undressed...

a. a typical external link looks like this:

<a href="//example.com">Ex. A. external link</a>

This is an external link, because it goes to example.com. How do I know your site is not http://example.com? (see 4)

b. an external link which opens in a new tab:

<a href="//example.com" >Ex. B. external link</a>

The extra attribute within the tag means the link will open in a new tab or window, whether it is an external link or not. (see note 5 for why http:// is replaced by // in our examples)

c. an external link marked with "rel":

<a href="//example.com" rel="external nofollow">Ex. C. external link</a>

You've heard of rel="nofollow" for nofollow links; but there are more options for rel. As many as are appropriate can be added to the value within quotes. Just leave a space between each word.

Link example C. will also open in a new tab, for either of my scripts #1 or #2. My small script #2 zeros in, like a heat seeking missle, on external links specifically marked with rel-external's (6). Then it fires its shot, and voila a ' target="_blank" ' attribute is inserted, unobtrusively into the link, in a brilliant flash of light.

easy DIY WordPress prep steps...

You can do this!

1. In the Wordpress Dashboard list of menus, go to Appearance > Widgets. Select it.

When the widget screen is open, look on the right side, at the prebuilt sections for your theme. These will almost always include "Sidebar" and a few other sections.

2. Your first task is to find a section there which meets the following criteria:

  • a section which you will always use
  • a section which falls lowest on every page and post

For example, in WordPress theme, "twenty-sixteen", you could use "Custom Bottom 2". Prebuilt section names vary by theme. In this example, we use the theme's "Footer Fullwidth" section.

Ready to put this into action?

Start your free journey today — no credit card required.

Decide on the section where the script will go:


3. Now that you have decided where the code snippet will go...

Click the Widget on the left side, labeled "Text".

When it opens choose the lowest part of the page or post that you always use. In this theme, that is called "Footer Fullwidth". Use the prebuilt section that you chose in the last step!

4. Let's continue with the example of "Footer Fullwidth", here.

Click on the arrow icon to open up the section.

You will see your brand new Text Widget in its list below it. Your new Text Widget will be blank. If you have other text widgets, for example Google Analytics, don't worry. This should not compete.

Leave the title blank, because in some themes, the title will show.on the page.


5. FINALLY: Paste the entire script, as is, into the "content" textarea field for the Text widget. Save it. In fact, watch it, and make sure it SAVES after you press the "Save" button. That's it! If you are using script #1, which automatically targets ALL external links, you're done!

6. Test it: browse to a page; locate a link that you know is not internal to your site; click it; and it will open in a new tab (or window, depending on your browser preference settings). Just for kicks, go back to your editor for that page, and look at the same link in code. Notice ' target="_blank" ' was actually NOT added to the page code. That's what is meant by "dynamic"—it only changes during a browser visit. Yea! Give yourself a hug.

which script to use: #1 or #2

GOAL 1: You would like all of your external links to open in a new tab, and your internal links to stay on your site. But if you ever change your mind, you'd like an automatic, split-second "undo".

SOLUTION 1: script #1 below. Instanteous, with instant undo.

GOAL 2: You would like only some of your external links to open in a new tab; but not all.

SOLUTION 2: script #2 below (full control)
Note this script does require you to add "rel="external" or rel="external nofollow" to each link you wish to control and have dynamically open in a new tab or window. Therefore, links without the rel-external value will be skipped over by this script. Script #2, thus, allows you complete control over which external links open in a new tab.

GOAL 3: Wordpress 4.5 update reportedly has deleted the "target" attributes of manually embedded links, in some cases. This may depend on one's theme, or if a child theme is in play. (Why did they do this? see again, note 1) You want to avoid the tedium of working through hundreds of pages and posts and links; but you do want your ' target="_blank" ' back, this very second, like yesterday, like now.

SOLUTION 3: use script #1 below; maybe later script #2. Instantaneous results.
If you want full control, eventually, but a quick fix NOW; install script #1, first. Then you can take your time to add rel="external" or rel="external nofollow" to only specific links you wish to target. Once that task is complete, simply replace script #1 with script #2. in the original widget and section. In the meantime, script #1 has you covered for ALL external links, automatically!

UNDO: To undo any solution, return to Appearance > Widgets; toggle open the section where you added the Text widget; toggle open the text widget; highlight the script and delete; then SAVE. That's it. It's easy because none of your pages or posts were actually changed by either script. In case you have added rel="external" to some links, don't worry. By themselves they do nothing, other than to identify the link as external to your site.

Fran's code:

Here is the code to add to a new Text widget inside your Footer or Custom Bottom, or a similar section prebuilt in your theme. Select one or the other per your goal.

Script #1 - All external links will dynamically open in a new tab or window

<script type="text/javascript" defer>function targetAllOutsideLinks(){var anchr,gettag=document.getElementsByTagName||undefined;if(gettag||document.links){var lnks=document.getElementsByTagName("a")||document.links;var lnkslen=lnks?lnks.length:null;if(lnkslen){for(i=0;i<lnkslen;i++){anchr=lnks[i];if(anchr.hostname!=window.location.hostname){anchr.target="_blank";}}}}}targetAllOutsideLinks();</script><!--dynamically adds target="_blank" to ALL external links in posts and pages, effecting an open to a new tab or window. Copyright 2016, Fran Corpier -->

OR...

Script #2 - Only external links having the attribute rel="external" or rel="external nofollow" or some other combination, including external, will open in a new tab or window, automatically. This script only targets those links.

<script type="text/javascript" defer>function targetRelExtLinks(){var anchr,aRel,gettag=document.getElementsByTagName||undefined;if(gettag||document.links){var lnks=document.getElementsByTagName("a")||document.links;var lnkslen=lnks?lnks.length:null;if(lnkslen){for(i=0;i<lnkslen;i++){anchr=lnks[i];aRel=gettag?lnks[i].getAttribute("rel"):(lnks[i].rel?lnks[i].rel:null);if(aRel){if(aRel.indexOf("external")!=-1){anchr.target="_blank";}else if(aRel.indexOf("popup")!=-1){anchr.target="newwin"}}else if(!gettag){if(lnks[i].hostname!=window.location.hostname){anchr.target="_blank";}}}}}}targetRelExtLinks();</script><!--dynamically adds target="_blank", to page and post links SPECIFICALLY marked with rel="external" (or rel="external nofollow"); effecting an open to a new tab or window. Copyright 2016, Fran Corpier -->


Of course, if you have any questions, or need a particular tweak, write me, or discuss, below.

Fran


Notes:

1. WordPress is structured around XHTML, which took the development community by storm in 2000. Since then HTML has come back in vogue (HTML5 to be exact.) The target attribute in a link does not validate in XHTML; but is in use again in a maturing HTML5. (see http://www.w3.org/TR/html5/links.html#attr-hyperli...)

2. see Google defn bounce rate : http://bit.ly/1hJDMLh
(URL shortened due to WA link policy)

3. We add it unobtrusively via JavaScript, so that "target" does not show up in your XHTML Page or Post; yet is rendered for the visitor's browser the millisecond they hit your content. XHTML validation ? check! Link opens in new tab ? check!

4. example.com, .org, .net, and .edu are set up specifically to use for examples in documentation; so that technical and software writers can avoid domain name conflicts in their examples. There is no permission or attribution required to use them in this manner. ICANN manages the web server to which these domains resolve, and where the www. subdomain is also defined for each.
(see IANA : https://www.iana.org/domains/reserved;
RFC 2606. [s 2] : http://tools.ietf.org/html/rfc2606#section-2; and
RFC 6761. [s 6.5] : http://tools.ietf.org/html/rfc6761#section-6.5)

5. The leading // for a link might look a bit odd; but the two forward slashes indicate flexible protocol. The result is that, if you are serving the page over http, the browser calls it as http://example.com. But if you are serving it over a secure connection, https:, then the browser calls example.com with https://example.com. Wordpress 4.5 seems to have finally made this their default linking method; although I haven't fully tested all functions.

6. see rel-external microformat : http://microformats.org/wiki/rel-external

Share this insight

This conversation is happening inside the community.

Join free to continue it.

The Internet Changed. Now It Is Time to Build Differently.

If this article resonated, the next step is learning how to apply it. Inside Wealthy Affiliate, we break this down into practical steps you can use to build a real online business.

No credit card. Instant access.

2.9M+

Members

190+

Countries Served

20+

Years Online

50K+

Success Stories

The world's most successful affiliate marketing training platform. Join 2.9M+ entrepreneurs building their online business with expert training, tools, and support.

Member Login

© 2005-2026 Wealthy Affiliate
All rights reserved worldwide.

🔒 Trusted by Millions Worldwide

Since 2005, Wealthy Affiliate has been the go-to platform for entrepreneurs looking to build successful online businesses. With industry-leading security, 99.9% uptime, and a proven track record of success, you're in safe hands.