Categories: Tips & Tricks

How to: Open external links in a new window

Over the weekend, I attended WordCamp Denver, and I was asked by John Hawkins how to force links to open in a new tab with out editing the source code. So, today lets learn a simple jQuery trick to open all external links in your site in a new tab or window. 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>

That’s it, just make sure you change the http://YOURSITE.com to your website.

Update

If you like you can remove the var $j = and replace all $j with simply just $

 

Web Master

Hi, I am Miguel, I bought this site in 2009. So I now run or manage the site. Please visit my new website or follow me on twitter @W3i.

Recent Posts

Contest: WP e-Commerce theme competition

The WordPress e-Commerce team are gearing up to announce a competition for the best WordPress…

4 hours ago

Arthemia Premuim

Arthemia Premium is a magazine style theme that unleashes the power of Wordpress, transforming it…

16 hours ago

Revolution Two: Album theme

Benefits include the Album theme, unlimited theme support answered by our experts, customization techniques with…

2 days ago

Search Unleased: A custom WordPress plugin

Most all WordPress theme's use a a simple search form to search your site. But…

2 days ago

Limit the characters that display on the_title

Ever wanted to display the title of a post somewhere but limit the amount of…

3 days ago