Join

Open All External Links in New Browser Tab

Don't want to mess with code snippets? Request for this to be a feature of MyListing Pro.

Instructions

  1. Create a new PHP code snippet.
  2. Copy the contents of code snippet below.
  3. Paste the contents into your code snippet.
  4. Review any notes that I’ve provided.
  5. Save and enable the code snippet.
  6. Test.

Snippet

Important: Something with how MyListing has been developed causes this code snippet to break links that aren’t even external links if you apply it to your entire website. You must ensure you only run this code snippet to highly targeted areas, and using WPCodeBox’s conditions feature assists with that.

Keeping people on your website is essential, and allowing external links to take people away from your website is typically not a good thing.

This code snippet modifies all external links on a webpage to open in a new browser tab. The code uses the DOMDocument class to parse the HTML and adds the target=”_blank” attribute to external links.

<?php

function modify_links_target($content) {
    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    $dom->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'));
    libxml_clear_errors();

    $xpath = new DOMXPath($dom);
    $links = $xpath->query("//a[@href]");

    foreach ($links as $link) {
        $href = $link->getAttribute('href');
        if (strpos($href, 'http') === 0 && strpos($href, $_SERVER['HTTP_HOST']) === false) {
            $link->setAttribute('target', '_blank');
        }
    }

    return $dom->saveHTML();
}

ob_start('modify_links_target');