Home / Admin / Open External link to a new tab
Duplicate Snippet

Embed Snippet on Your Site

Open External link to a new tab

This code snippet enhances a WordPress website by automatically opening external links in new tabs. When applied, the script runs after the page has loaded, identifying all hyperlinks within the content. If a link's destination differs from the current page's hostname, it modifies the link attributes to ensure it opens in a new browser tab, enhancing the user experience. This functionality improves website navigation by providing a seamless transition for visitors accessing external resources, contributing to a more user-friendly browsing environment.

Code Preview
function open_external_URL_in_a_new_tab() {
        document.addEventListener('DOMContentLoaded', function () {
            var links = document.querySelectorAll('a');
            links.forEach(function (link) {
                var url = link.getAttribute('href');
                var parsedUrl = new URL(url, window.location.href);
                if (parsedUrl.hostname !== window.location.hostname) {
                    link.setAttribute('target', '_blank');
                    link.setAttribute('rel', 'noopener noreferrer');
add_action('wp_footer', 'open_external_URL_in_a_new_tab');


Add a Comment