Wordpress Snippets

Open All External Links In New Window

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>

Hire Us. Or just say Hi!
Need a job? Apply to get one.