Tiny script opens external links in new tab: easy
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.
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
Recent Comments
62
Very informative and helpful. Thanks for your efforts on this...As others have, I too have bookmarked this! Cheers! Dave : )
Hi, Dave!
Whoo, glad it was something valuable enough to bookmark.
If you ever want to put it into play, and have questions, feel free to PM, or post them here.
Thanks so much for taking time to leave a comment!
--Fran
A really thorough and well written article, congratulations. Not to mention the solution to the situation with vanishing external links :)
Bravo!
Ervin, so nice to meet you. A very nice complement from a fellow developer.
I just clicked over to your barefoot running site. Wow. I wonder if I can get some of these shoes in the U.S. I suppose so.
Thanks!
--Fran
You are so awesome to have taken the time to write all this up and then, in detail, respond to everybody's questions. Thank you so much! God Bless! ~Cathy
Cathy, thank you for your sweet comment. I'm thinking I may need to cut down the jargon and update this week. What do you think?
--Fran
I'm thinking it's too hard to please all the people all the time, and that some of the people can be pleased some of the time. What do you think? :-)
great information! now I just have to figure out what it all means lol :) guess I'm in the same boat as Genie and Konkers. Lots of technical jargon. I have done a recent post where I referenced a previous post, and added an internal(?) link to the previous post(that opens in a new tab that goes to the post referenced). i thought I read somewhere that this is a good thing to do. sorry for rambling post...just trying to learn. Thanks Fran
-KJ
Hello, Kevin. Okay, let's see if I can unwind that. All of these posts are on the same site. Correct? Let's see if I follow the trail correctly:
newPost1 > oldPost1 > newPost1 (in new tab)
Is that correct? I'll continue this reply, once I know my assumption is correct or is corrected by you.
yes, that is how i have it set up. since I'm not much of a techie....my description would be: wrote a post on a particular person. published. have written a new post that mentions same person. in that new post where he is mentioned, I linked his name back to my 1st post. when clicking his name in new post it opens a new tab back to the original post about him. (new post not published yet- having issues about photo rights, etc....because it deals with movie stars) whew! i know your way of explaining this is easier/better, but I think I lack the necessary language for this :(
thanks Fran!
There's nothing wrong with posts linking to each other, as long as the links appear as something that might naturally appear. A home page can have a huge impact on internal pages by linking to them. (In fact, that is probably the best argument for the home page being a blog roll.)
Is one or more of these in a "Related reading" section, which has other internal links ? [√ - this is fine - it serves a similar purpose as an article site's category index page]
Is the link text (technically called the "anchor text" or "link label") related to the keyword phrase (technically "keyword" or "longtail keyword") for the article linked to? [√ - an excellent strategy]
Is either of the links found within the actual text (technically the "copy") of the article—in other words within an actual sentence, rather than as a stand-alone link? [√ - the best kind of link]
Are your internal links complete URLs, as in "http://{your-domain.com}/your-page.html" ? [√ - that's good, because that's how others will be linking to them from the outside, too]
Now, as to the benefit of opening your own internal page in a new tab; I can't answer that. There couldn't be any SEO benefit. So this is a determination you have to make based on a balance between the convenience of your visitor, and your goals for your page.
Kevin, you've inspired me to come up with a decent article on linking.
Hope this validates your internal linking strategy, and maybe adds some insight, too. Let me know if you have any more questions in this regard.
--Fran
thanks so much Fran! a detailed and descriptive response, thanks for taking the time to do this. my links are found within the copy, yes. as far as them being complete URLs, yes, to the best of my knowledge. I feel like I'm kinda starting to get this now :)
Sounds like you are getting it just right, Kevin!
Most of the time you have to "hardcode" (that means "directly type") links in WordPress to include your complete URL. Often, plugins, and maybe WP, itself, will use "relative" URLs, if the link points to your own domain. That's okay for images, scripts, and css; but for pages and posts, full links are best for SEO.
--Fran
You're the sort of WA member I like to follow. Looking forward to reading more of your blogs. :-)
Well after that delightful attribution, how could I not check out your profile. I love your background and we have some things in common, there. Thanks for following and commenting, especially, Ian!
--Fran
It's understandable. I knew how easy it was of course; but you were frustrated over the state of a couple hundred or more pages and posts, following the 4.5 update. Anybody, in your shoes, would be. No doubt, the last thing you wanted to do at that moment was wrangle something unfamiliar.
I'm just so happy that you found a quiet moment to do this, Loes, and that it solves your immediate problem, as well as potentially future ones, too.
--Fran
I thought I was following you, too, frankly; because I've read a number of your posts. :)) Done. lol. Thanks, Loes.
I think I need this, but I don't understand it. I was looking for an answer to the question of how to embed a link into text. I think this is what you are talking about but it is going completely over my head. Can you do an embedding for dummies version?
Jeanie, I apologize. I'm so accustomed to writing for technical junkies (or art enthousiasts—a yet different style), I realized that even the bit of jargon I used in this article is too much. It definitely needs a rewrite. Thanks for being honest.
Now let's talk about your need. It may be different; so I want to understand it. Then I can help.
You want to know how to embed a link into your posts and pages?
In the editor, where you are adding your text, click on VIEW, not on TEXT at first. In view mode, you will see two icons on the top row, that look like chain links. Click the broken chain link on the right, to UNLink, or the whole one on the left, to create a new LINK. (see image below).
It opens a new style "inline" link editor in WP 4.5. But if you click the Gear Icon to its top right, it will open up a more familiar, full link editor. (see my 2nd illustration in the attached images, below).
They have a very nice feature, to either search for or select a page or post from a list of your existing ones, to help you link to an internal page, with no muss no fuss. My 2nd illustration show more.
Does this answer your question, Jeanie?
--Fran
Yes, thank you. I think the second one is what I want. I can't do it right now but I will keep this and let you know. Appreciate your response.
Okay, Keith. I understand—one step at a time. Once you start placing affiliate links or reference links on your posts and pages, then come back and check this post out. And I'm happy to answer any questions. Thanks for letting me know you read it! :D
--Fran
See more comments
Thank you for the long explanation. I have no computer background but your explanation was easy to digest.
I will put your solution on my sites.
Arief, I'm happy that this can help you. Do, please, let me know if you have any questions.
--Fran