How to Make All External Links Open in a New Tab Without Plugin?
How to add target=”_blank” parameter to open the link in a new window or tab.
1 Answers
Best Answer
Add this line of code to the functions.php file or with WP Code Plugin in PHP Snippet.
function open_urls_in_new_tab($content) {
$excluded_domain = 'example.com';
$pattern = '/<a(.*?)href=["\'](.*?)["\'](.*?)>/i';
$replacement = '<a$1href="$2"$3'; $content = preg_replace_callback($pattern, function($matches) use ($excluded_domain, $replacement) { $url = $matches[2]; if (strpos($url, $excluded_domain) !== false) { return $matches[0]; } else { return str_replace('>', ' target="_blank">', $matches[0]);
}
}, $content);
return $content;
}
add_filter('the_content', 'open_urls_in_new_tab');
add_filter('widget_text_content', 'open_urls_in_new_tab');
Note: Replace example.com with your own domain name, without HTTP or HTTPS.