Set a global target for all external links

How can I automatically open all external links in a new window?

When you have a website with external links, it’s preferable that these links open in a new window, so that the visitor can return to your website once the external page has been consulted.

In WordPress, it takes several manipulations to force a link to open in a new window (target blank). This simple function allows you to force the links to open in an external window.

[php]
<?php

/**
* Set global target blank for all external links
*/
function wpster_outbound_links_new_window($content) {
return preg_replace_callback(‘/<a[^>]+/’, ‘wpster_outbound_links_new_window_callback’, $content);
}
function wpster_outbound_links_new_window_callback($matches) {
$link = $matches[0];
$site_link = get_bloginfo(‘wpurl’);
if (strpos($link, ‘target’) === false) {
$link = preg_replace(“%(href=\S(?!$site_link))%i”, ‘target=”_blank” $1’, $link);
} elseif (preg_match(“%href=\S(?!$site_link)%i”, $link)) {
$link = preg_replace(‘/rel=\S(?!nofollow)\S*/i’, ‘target=”_blank”‘, $link);
}
return $link;
}
add_filter(‘the_content’, ‘wpster_outbound_links_new_window’);
add_filter(‘comment_text’, ‘wpster_outbound_links_new_window’);
?>
[/php]

Submit a Comment

Your email address will not be published. Required fields are marked *