htmlcsswordpresshyperlinkexternal-links

Open every external link in a new window automatically (html, css)


I am searching for an option to open every external links from my website (wordpress-blog) to any other sites automatically in a new window. Is that with css or html possible without doing it 1000 times manually via hand as "target _blank"?

Thank you so much!

PS: sry for my bad english, I am no native speaker :(


Solution

  • Put this code in your theme functions.php file.

    function cdx_handel_external_links() {
        ?>
    <script type="text/javascript">
    ( function( $ ) {
    
        $("a[href^=http]").click(function(){
          if(this.href.indexOf(location.hostname) == -1) {
             $(this).attr({
                target: "_blank"
             });
          }
        })
    
       //Add Nofollow
       $("a").each(function(){
        if(this.href.indexOf('nytimes.com') >0 ){
            $(this).attr({
                rel: "nofollow"
             });
        }
       });
    
    } )( jQuery );
    </script>
       <?php
    }
    add_filter( 'wp_footer', 'cdx_handel_external_links', 999);