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

Embed Snippet on Your Site

Open External Link in New Tab in WordPress

PHP Snippet

<10
Code Preview
php
<?php
add_action('wp_footer', 'open_external_links_in_new_tab');
function open_external_links_in_new_tab() {
    ?>
    <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>
    <?php
}

Comments

Add a Comment