No CSS Solution
In an ideal world, I would be able to use a CSS selector to add this to all my links. But CSS is specifically for display purposes, and not functionality. Since the target=”_blank” section is an attribute of an existing HTML element and doesn’t relate to an ID, or a class, it’s not something that we can do.
Get Familiar with CSS Selectors
In the example below, I’m going to be using a single <div> element with a certain ID in order to select the links to which I want to add the target=”_blank” code. However, your selection needs are likely to be different. You might want to select a class instead of an ID. Or more crucially, not select a certain subsection of elements.
For this, it’s best to get familiar with the jQuery selection operators. Or (like me), simply search on Google for someone with the same problem 🙂 . In fact, I recommend the latter approach. Find a question on stackexchange by a person with similar needs, and then modify that solution to suit your needs. It’s what works for me every time!
Here’s the link to which I want to add the target blank code. Note that it’s encased inside a <div> element with the ID “some_id”:
Adding the Code to the Footer
Since our operation is unlikely to be time-sensitive and is not going to be affecting the rendering of the pages in any way, there’s no need to place our code in the header of the document, or even the main body. In fact, we want to place it as far down as possible so that the entire HTML document has already been rendered.
For this, the footer is the natural place to put our code. Over there, it won’t interfere with anything other plugins, and will run after the user has already started to read the page. No one is going to immediately click a link in the first 0.5 seconds of opening a page!
Here’s the code you need to add to WordPress to accomplish this:
In the above code, I’ve selected the <div> element with the ID “some_id”, and added the attribute target=”_blank” to it. If you don’t know how to add code like this to WordPress, check out our tutorial on NameHero that explains how to do it step by step.
Once you’ve added this code and saved it, it should find all the links specified by the selector and added the target blank attribute to it as shown in the screenshot here:
And that’s it! A perfect solution that doesn’t require any kind of 3rd party file. The code is small, and runs at the end of the page load, which makes it ideal!
I’m a NameHero team member, and an expert on WordPress and web hosting. I’ve been in this industry since 2008. I’ve also developed apps on Android and have written extensive tutorials on managing Linux servers. You can contact me on my website WP-Tweaks.com!