Programming

Automatically open external links in new tab

Do you want to open all the external links of your website in a new tab ? If you say ‘YES“, just copy the  following code and paste it in your function.php file.

 

/*
* OPen external links in a new tab
*/
add_action( 'wp_head', 'procab_openlinks_innnewtab' );
function procab_openlinks_innnewtab() { ?>
    <script type="text/javascript">
        jQuery(document).ready(function($){
            $('a[href]:not([href^="<?php echo site_url(); ?>"]):not([href^="#"]):not([href^="/"]):not([href*="javascript:void(0)"]):not([href^="tel"]:not([href^="mailto"])').attr( 'target', '_blank' );
        });
    </script>
    <?php
}

 

The aforementioned script excludes, if teljavascript.void(0), hash(#), mailto and site_url() are in the href of the anchor tag.

Views: 24

Standard