I have no clue how to deal with the link opening in my posts

Browser: Chrome 110
OS: macOS / Windows / Linux / etc.
URL: Link to a page that illustrates this issue
Video: Short screen recording that illustrates this issue (free tool: jam.dev)

Hi folks,

I’m rebuilding my Elementor site using Bricks, and I ran into an issue.

I like to write posts using the Markdown editor from GitHub (GitHub - terrylinooo/githuber-md: Markdown editor plugin for WordPress.). In the editor settings, I always choose for links to open in a new tab to improve user experience.

However, this time it doesn’t seem to work. On my old site built with Elementor, it worked as expected.

I wonder if anyone has run into this before or knows how to fix it. It’s really important for me that links open in a new tab.

Thanks in advance!

I found that on my friend’s site built by bricks, it worked, I wonder what’s wrong with it!

Hey Mezzy,

Just a heads-up — this plugin has been closed since October 8, 2024 due to a security issue. Because of that, I personally wouldn’t recommend using it anymore (it may have vulnerabilities), but of course it’s up to you.

To make your links open in a new tab in posts, you have two options:

  1. Add attributes manually
    Use target="_blank" and rel="noopener" directly in your links. (Safer and more precise.)
  2. Use a custom snippet
    If you’d rather automate it, here’s a little snippet that forces all links in post content to open in a new tab and adds the rel="noopener" attribute:
<?php
add_filter('the_content', function ($content) {
    if (is_admin() || stripos($content, '<a ') === false) return $content;

    libxml_use_internal_errors(true);
    $dom = new DOMDocument('1.0', 'UTF-8');
    $dom->loadHTML('<?xml encoding="utf-8" ?>' . $content);

    foreach ($dom->getElementsByTagName('a') as $a) {
        $href = $a->getAttribute('href');
        if (!$href) continue;
        if (strpos($href, '#') === 0) continue;
        if (preg_match('~^(mailto:|tel:|javascript:)~i', $href)) continue;

        // open in new tab
        $a->setAttribute('target', '_blank');

        // ensure rel contains noopener (merge with existing)
        $rels = preg_split('/\s+/', trim($a->getAttribute('rel')), -1, PREG_SPLIT_NO_EMPTY);
        $rels[] = 'noopener';
        $a->setAttribute('rel', implode(' ', array_unique($rels)));
    }

    $html = $dom->saveHTML($dom->getElementsByTagName('body')->item(0));
    return preg_replace('~^<body>|</body>$~i', '', $html);
}, 20);
?>

This snippet works globally, so it’s not always ideal. Personally, I’d stick with adding attributes manually for more control.