In this article I will cover 5 different methods on how to open all links in new tab on WordPress website.
To force opening all links in a new tab there are couple of solutions:
1. WordPress plugin
Open Links In New Tab is a WP plugin that opens internal and external links in a new tab. You can set if you want to open internal links in new tab, or external links in a new tab or both.
2. base target _blank
Open the header file from your custom theme and add
<base target="_blank"/>
The “base” tag in HTML head will force all links on the page to be opened in new tab.
3. Custom code in functions.php
/*
* Add target blank to content links
*/
function wp_add_target_blank($content) {
// Get the site url
$site_url = get_site_url();
// Get all the links in the article
preg_match_all('#<a ([^>]*)>#i', $content, $matches);
// Loop through each link
foreach ($matches[1] as $key=>$value)
{
// If link does not contain the site_url or the text _blank, add target="_blank"
if (!stristr($value, $site_ul) && !stristr($value, '_blank'))
{
$content = str_replace('<a '.$value.'>', '<a target="_blank" '.$value.'>', $content);
}
}
// Return the modified content
return $content;
}
// Add the wordpress filter
add_filter( 'the_content', 'wp_add_target_blank' );
4. JavaScript
Add this fancy JS snippet inside your active theme’s functions.php or footer.php template:
<script>
var all_links = document.querySelectorAll('a');
for (var i = 0; i < all_links.length; i++){
var a = all_links[i];
if(a.hostname != location.hostname) {
a.rel = 'noopener';
a.target = '_blank';
}
}
</script>
If your theme includes ECMAScript 6 you can also use:
new Set(
Array.prototype.filter.call(document.querySelectorAll('a[href],area[href]'), function(acc, el) {
el.href[0] !== '#' && acc.push(el)
return acc
}, [])
).forEach(function(href) {
window.open(href, '_blank')
})
5. jQuery
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('[href*="mail"]').attr('target','_blank');
});
</script>
We can also select all anchor tags that have rel=”external”, and set attribute:
<script type="text/javascript">
$('a[rel="external"]').attr('target', '_blank');
</script>
Was this post helpful?
Let me know if you liked the post. That’s the only way I can improve. 🙂