Open WordPress external links in a new window automatically

Open WordPress external links in a new window automatically

Tired of going to the Gutenberg editor and saying open in a different window every time you add an external link? Now you don’t have to manually this. Let’s add some code and automatically open new links in a new window.

If you know a code a little bit you will understand we will add target=”_blank” programmatically.

The code below is for open links in a new window. But please consider, all your external links open in a new window, not only your post.

You should add the following code into your functions.php.

// Adding target="_blank" to external links
function amc_add_targetblank_to_external_links($content) {
    return preg_replace_callback('/<a[^>]+/', 'amc_add_blank_to_nofollow_callback', $content); 
function amc_add_blank_to_nofollow_callback($matches) {
    $link = $matches[0];  
    $site_link = get_bloginfo('url');   
    $site_link_parsed = parse_url(get_bloginfo('url'));   
    $site_link_host = $site_link_parsed['host']; 
    $link = preg_replace("%(href=\"https?:\/\/(?!$site_link_host|www.$site_link_host))%i", 'target="blank" $1', $link); 
    return $link;

add_filter('the_content', 'amc_add_targetblank_to_external_links'); 

If you have any questions feel free to ask me in the comments.

Comments (0)
Join the discussion
Read them all


Hide Comments

This is a unique website which will require a more modern browser to work!

Please upgrade today!