Home / Admin / Open All Internal and External Link in New Tab in WordPress
Duplicate Snippet

Embed Snippet on Your Site

Open All Internal and External Link in New Tab in WordPress

Open All Internal and External Link in New Tab in Wordpress

Code Preview
php
<?php
function open_internal_links_in_new_tab() {
    echo '
    <script type="text/javascript">
    document.addEventListener("DOMContentLoaded", function() {
        const domain = window.location.hostname;
        const links = document.querySelectorAll("a[href^=\'http\']");
        links.forEach(link => {
            if (link.hostname === domain) {
                link.setAttribute("target", "_blank");
                link.setAttribute("rel", "noopener noreferrer");
            }
        });
    });
    </script>';
}
add_action('wp_footer', 'open_internal_links_in_new_tab');

Comments

Add a Comment