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?


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!

  • works like a charm!, thanx – anandmongol Feb 8 '17 at 12:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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