0

I'm using this code to open all external links in new window (site is based on Wordpress):

/* OPEN ALL OUTBOUND LINKS IN NEW TAB */
function autoblank($text) {
$return = str_replace('href=', 'target="_blank" href=', $text);
$return = str_replace('target="_blank"
href="https://example.com',
'href="https://example.com', $return);
$return = str_replace('target="_blank" href="#', 'href="#', $return);
$return = str_replace(' target = "_blank">', '>', $return);
return $return;
}
add_filter('the_content', 'autoblank');
add_filter('comment_text', 'autoblank');

Unfortunately it's not perfect because it also opens internal links in new window (only if these are placed in posts or pages - menu items etc. open normally). Does anyone have an idea how to modify this code to not open internal links in new window?

-1

Way to complicated to do this with php in WordPress, I'd advice on doing this on the frontend with a bit of jquery magic. I wrote a tiny jQuery plugin that opens all external links (all links with another domain/host name than the current site) in a new window.

Check out the plugin: https://www.npmjs.com/package/jquery.jold.external-hrefs

To do this manually, without the plugin is pretty simple too:

$('a').each(function() {

    /** Get the current hostname */
    var a = new RegExp('/' + window.location.host + '/');

    /** Check if the href attribute of the link has a different hostname than the current site */
    if( !a.test(this.href) ) {

        $(this).on('click', function(event) {

            event.preventDefault();
            event.stopPropagation();

            /** Create an url object for the link */
            url = new URL(this.href);

            /**
             * Check if the links is a http protocol link
             * otherwise just open all other link protocols (tel, mailto)
             */
            if (url.protocol == 'http:' || url.protocol == 'https:') {
                window.open(this.href, '_blank');
            } else {
                window.location.replace(this.href);
            }

        });
    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.