Open all external links in a new tab

Linking is important. Whether you need to create a link to posts and pages on your own site (internal links) or you want to lead your visitor outside your domain (external links), WordPress gives you the opportunity to build those links easily.

All you will have to do is select a letter, word, entire phrase, image or any other object from which you want to create a link. Then you click on “link” button located on top of your editor and enter a destination URL. If you’re more into old-school HTML coding, you can write a tag yourself (don’t forget to use text editor for that).

It is the unwritten rule that all internal links should be opened on the same page while those external should be opened in the new tab/page. The logic is simple – if you lead a visitor to an external site which is opened on the same page, you are instantly closing your own site and that’s something you don’t want to do.

Opening links in new tab require you to check the box in the link creation lightbox, but sooner or later you will forget to click on the little box and writing HTML code manually will be something you want to avoid by any means.

Instead of worrying about which links are opened in new tab/window, you can use this little code which will do its magic and open all external links in new tab/window automatically.

Automatically open external links in new tab:

  1. Open footer.php file
  2. Copy and paste the following code before body and html closing tags:
  3. <script type="text/javascript">
    //<![CDATA[
    jQuery(document).ready(function($) {
    $('a').each(function() {
    var a = new RegExp('/' + window.location.host + '/');
    if(!a.test(this.href)) {
    $(this).click(function(event) {
    event.preventDefault();
    event.stopPropagation();
    window.open(this.href, '_blank');
    });
    }
    });
    });
    //]]>
    </script>
    
  4. Save changes

After making these changes to your footer.php file, all of your links which are leading outside your domain will be opened in a new tab while other ones will stay intact. Now you don’t have to worry about links which you forgot to check as “opened in new window” and you relax when creating a new link in your articles.

Similarly, you can link your post title directly to any external URL.

START YOUR OWN BLOG

This guide is an introduction to mastering the art of blogging. It provides easy to follow steps to start, maintain, and grow your blog.

Read the guide

4 thoughts on “Open all external links in a new tab

Leave a Reply

Your email address will not be published. Required fields are marked *