Home » Blogger Hacking

Open every external link of wordpress in new window

12 January 2010 No Comment

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');
The code is very simple. First of all I fetch the name of my blog. For example http://www.djrohan.com will gives me only djrohan.com . Then I get all the links in the post content into an array.

Related Posts

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.