Here's a WordPress snippet you can add to your theme's functions.php
file (or a site-specific plugin) to make all external links open in a new window (i.e., add target="_blank"
automatically):
✅ WordPress Snippet (PHP + JavaScript approach):
// Add this to functions.php or a site-specific plugin
// https://websitefunctions.comfunction wp_external_links_new_window() {
?>
<script>
document.addEventListener('DOMContentLoaded', function () {
const links = document.querySelectorAll('a[href^="http"]');
const currentHost = location.hostname;
links.forEach(link => {
const linkHost = (new URL(link.href)).hostname;
if (linkHost !== currentHost) {
link.setAttribute('target', '_blank');
link.setAttribute('rel', 'noopener noreferrer');
}
});
});
</script>
<?php
}
add_action('wp_footer', 'wp_external_links_new_window');
✅ Explanation:
-
It waits until the DOM is fully loaded.
-
It selects all links starting with
http
(i.e., absolute URLs). -
It compares each link's hostname to the current site's.
-
If the link is external, it sets
target="_blank"
and addsrel="noopener noreferrer"
for security.