/* Warning: Use AND/OR modify at your own risk. */
function getRootDomain($url) {
$urlParts = parse_url( $url );
if ( $urlParts && isset( $urlParts['host'] ) ) {
return $urlParts['host'];
}
return false;
}
function rewriteExternal($html) {
$domain = str_replace('.', '\.', getRootDomain(get_site_url()));
//var_dump($domain);
// The url for your redirection script
$prefix = 'http://www.example.com?goto=';
// a regular expression to determine if
// this link is within your site, edit for your
// domain or other needs
$is_internal = '/(?:^\/|^\.\.\/)|'.$domain.'/';
$dom = new DOMDocument();
// Parse the HTML into a DOM
$dom->loadHTML($html);
$links = $dom->getElementsByTagName('a');
foreach ($links as $link) {
$href = $link->getAttribute('href');
if (!preg_match($is_internal, $href)) {
$link->getAttributeNode('href')->value = $prefix . $href;
$link->setAttributeNode(new DOMAttr('rel', 'nofollow'));
$link->setAttributeNode(new DOMAttr('target', '_blank'));
}
}
// returns the updated HTML or false if there was an error
return $dom->saveHTML();
}
function outboundLinksModifier( $content ) {
if ( is_main_query() /* && is_singular( 'specific_post_type_or_types' ) */) {
return rewriteExternal($content) ;
}
}
add_action( 'the_content', 'outboundLinksModifier', 10, 2 );