How to Automatically Open Every External Link in a New Tab, Without a Plugin or JavaScript

Opening external links in a new tab can increase the chance of the user coming back to your site. Configuring it manually for each link is a tedious task. Learn how to do it automatically.

Opening external links in a new tab is a good practice – it is less disorienting, and might increase the chance of the user coming back to your site. Configuring it manually for every link is a tedious task and one you are bound to miss every once in a while.

The block editor has a special toggle – but you still have to remember to use it. You can use a plugin – but as a rule of thumb, it is a good idea to minimize the number of plugins your site consists of. You can use JavaScript, but it can get clunky (even more so if your site is using AMP) and the result isn’t cacheable. So, none of these existing options for opening external links in a new tab is great.

Luckily, there is an automatic non-plugin non-JavaScript option. It is another case where the mother of all WordPress hacks comes in handy:

add_action('wp_head', 'buffer_start'); function buffer_start() { if (!wp_doing_ajax()) { ob_start('callback'); } } add_action('wp_footer', 'buffer_end'); function buffer_end() { if (!wp_doing_ajax()) { ob_end_flush(); } } function callback($buffer) { $patterns = []; $patterns[0] = '/<a([^>]*?)href=["|\']https:/'; $patterns[1] = '/<a([^>]*?)target="_blank" rel="noopener" href=["|\']https:\/\/frugalwp.com/'; $replacements = []; $replacements[0] = '<a${1} target="_blank" rel="noopener" href="https:'; $replacements[1] = '<a${1} href="https://frugalwp.com'; ksort($patterns); ksort($replacements); $buffer = preg_replace($patterns, $replacements, $buffer); return $buffer; }
Code language: PHP (php)

IMPORTANT: Replace frugalwp.com with your domain.

This code filters the entire page HTML. It adds target="_blank" rel="noopener" to all links and then removes them from internal links (that starts with your domain).

Notable code points:

  • It only adds target="_blank" rel="noopener" to links starting with a protocol. Meaning, it doesn’t add to relative links – which is great.
  • It adds rel="noopener" for security reasons, as recommended by Google.
  • The use of rel="noopener" also prevents the code from overriding special cases where you set internal links to open in a new tab.
  • It is client-side independent.
  • The result is cachable (by a dynamic cache).

Conclusion

Another great use of the mother of all WordPress hacks allows you to easily and securely open all external links in a new tab.

External links

Leave a comment

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