Open All External Links In New Window

How to Open All External Links In New Window

in Functions
Google+ LinkedIn

Almost all web sites provide links to other sites, but it’s generally good practice to open these “external” links in a new window or tab. This makes it clear that the content is not part of your site, and also leaves your site open in the browser so the user can easily return.

To make a link open in new window or tab, you can add target=”_blank” attribute in link straight with HTML. The only problem is that, it’s invalid markup. But you can accomplish this easily with jQuery.

Just paste this jQuery snippet in footer.php of your theme.

<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>

Share the love

If you like this snippet, share it with others!

4 Replies on "Open All External Links In New Window"

  1. Gef

    Nice tip, thank you a lot! sadly this seems not to work with the_excerpt “read more” link. Any clue?

    Regards, Gef.

    1. Sorry I did not follow.
      What is not working with `the_excerpt`.

      It’s JavaScript code, not PHP.

  2. Joel

    This is exactly what I was looking for. Worked like a magic for my wordpress theme. I wish you could just post this on the wordpress forum

    1. Joel, glad you found it valuable. Looking forward to hearing much more from you.

Leave a Reply

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