Open every external link of wordpress in new window
In this small tutorial I’ll explain how to open all external links in new window automatically. There are many ways for it but now I’ll only explain two of them – with and without jQuery. So let’s start.
Tutorial First – With jQuery:
We are going to make sure you have jQuery active on your site, you can do this easily in WordPress, since it’s bundled with the latest installations. Use this code in your header: <?php wp_enqueue_script('jquery'); ?> then, below the wp_head add the following:
<script type="text/javacript">
var $j = jQuery.noConflict();
$j(document).ready(function() {
//external attribute
$j("a:not([@href*=http://YOURSITE.com/])").not("[href^=#]")
.addClass("external")
.attr({ target: "_blank" });
}
);
</script>
Second tutorial – Without jQuery:
First open your theme’s functions.php file. If there isn’t any, create it. Append the following code in your functions.php file.
That’s it, just make sure you change the http://YOURSITE.com to your website.
Then I loop through the every links URL (href) and check if the domain name exists in that URL. If it does then it simply do nothing. If it does not exists then the code will append the target=”_blank” attribute to every link.
function external_links_newwindow($content){
preg_match('@^(?:http://)?([^/]+)@i',get_bloginfo('url'), $matches);
$host = $matches[1];
preg_match_all( '/<a(.+?)href=\"(.+?)\"(.*?)>(.+?)<\/a>/', $content, $matches );
foreach($matches[2] as $match){
if(!preg_match("|$host|i", $match))
$content = str_replace("href=\"$match\"","href=\"$match\" target=\"_blank\"",$content);
}
return $content;
}
add_action('the_content', 'external_links_newwindow');









Leave your response!