4

The following code in function.php, works fine for making the links - clickable,

add_filter( 'the_content', 'make_clickable',    12 );

But can I make the links to open in new tab?

1 Answer 1

4

I am not sure if there's a native function for this, but a little regex might help the case:

function open_links_in_new_tab($content){
    $pattern = '/<a(.*?)?href=[\'"]?[\'"]?(.*?)?>/i';

    $content = preg_replace_callback($pattern, function($m){
        $tpl = array_shift($m);
        $hrf = isset($m[1]) ? $m[1] : null;

        if ( preg_match('/target=[\'"]?(.*?)[\'"]?/i', $tpl) ) {
            return $tpl;
        }

        if ( trim($hrf) && 0 === strpos($hrf, '#') ) {
            return $tpl; // anchor links
        }

        return preg_replace_callback('/href=/i', function($m2){
            return sprintf('target="_blank" %s', array_shift($m2));
        }, $tpl);

    }, $content);

    return $content;
}

add_filter('the_content', 'open_links_in_new_tab', 999);

The patterns might need a little improvements. Hope that helps!

1
  • works like a charm!, thanx Commented Feb 8, 2017 at 12:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.