1

Who wants a virtual warm chocolate chip cookie?

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

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?

Lena Shore
  • 45
  • 7

1 Answers1

3

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.

dave
  • 62,300
  • 5
  • 72
  • 93
  • Didn't think of jquery. Good idea. For some reason, it's not working though. I must be doing something wrong. I'll keep at it. Thank you! – Lena Shore May 14 '15 at 19:31