Automatically add target=”_blank” to external links

Automatically add target=”_blank” to external links

In the functions.php file add these lines:
<?php
function open_external_links_in_new_tab($content) {
	return preg_replace_callback('/<a[^>]+>/', function$matches) {
		return preg_replace('/(href=["\']https?\/\/?!yourdomain\.com))/', '$1 target="_blank"', $matches[0]);
	}
}, $content);
add_filter('the_content', 'open_external_links_in_new_tab');

Donʼt let users leave your site too soon. External links? New tab! 🪟✨