• I need to find the code I can use in functions.php that opens external links in the new window. I know there are plugins and javascript, but I already have too many plugins and jscripts loading.

    I did find a script that seems to be working (see below), unfortunately, it opens all links in the new window including internal links.

    Can someone help me find the code that only opens external links in the new window that can be used within functions.php file?

    ———opens all links new window—————–

    /* 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://bigapplemedia.com’,
    ‘href=”https://www.bigapplemedia.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’);

    • This topic was modified 5 years, 9 months ago by Gene-M.

    The page I need help with: [log in to see the link]

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    Your code is first altering all links, then attempting to undo the alteration in certain circumstances. You are better off in this situation using preg_replace() to only alter links you actually want altered and leave all else alone. One line to replace four and do it better. Matching exact complex strings is inherently fragile. preg_replace() matches defined patterns instead, which is much more robust.

    The key is coming up with the right regular expression (regexp) that matches all the right links and none of the wrong links. There are online tools to help you do this, for example regexr.com. In the text field, enter all possible types of link HTML you want the regexp to address. Both to match and to not match. Experiment with the regexp expression until you get the desired matches.

    Use capture groups to take elements from the regexp and use them in the replacement string. If you’ve not used regexp before, it’s going to take some studying and experimenting to get things just right. IMO it’s well worth learning. Regexp is a very powerful matching expression that is widely used in programming.

    One of your regexp tasks is to capture the href attribute value so it can be used in the replacement string. You should be able to figure out how to capture any URL. Capturing any URL except yours is more advanced. I’ll give you a hint for that: use a negative look ahead in the form of (?!ABC) which will discard any match in the subsequent expression that is ABC. Replace ABC with any other expression, such as your domain name.

Viewing 1 replies (of 1 total)
  • The topic ‘How to Open External Link in new Window using Function.php’ is closed to new replies.