WordPress php function to open all outbound links in new tab

Who wants a virtual warm chocolate chip cookie?

I’m looking for a WordPress php function to open all outbound links in new tab.

Read More

I have found a couple of function solutions similar to the one below, but they only work for posts/pages and not for items hard-coded into the theme (like social media buttons):

/* OPEN ALL OUTBOUND LINKS IN NEW TAB */
function autoblank($text) {
$return = str_replace('href=', 'target="_blank" href=', $text);
$return = str_replace('target="_blank"
href="http://csihealth.lenadev.com',
'href="http://csihealth.lenadev.com', $return);
$return = str_replace('target="_blank" href="#', 'href="#', $return);
$return = str_replace(' target = "_blank">', '>', $return);
return $return;
}
add_filter('the_content', 'autoblank');
add_filter('comment_text', 'autoblank');

Is there a way to alter this so it works for all outbound links? Not just posts/pages?

Related posts

Leave a Reply

1 comment

  1. You could do it with jQuery:

    $(function() {
        $( 'a[href^="//"],a[href^="http"]' )
        .not( '[href*="' + window.location.hostname + '"]' )
        .attr('target', '_blank');
    });
    

    This will find any link that is not a relative link (so, any that could be outbound), then removes those that actually do point to your own site, and set the target to blank for those that are left.