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');