I've got two options for this plugin.
(1) nofollow all external links in content
and/or
(2) no follow links to this target folder (enter the absolute url to the target folder)
In option 2, the links could be internal OR external.
Both options can be set, neither option may be set, or a single option may be set.
if(get_option('my_nofollow') || get_option('my_nofollow_folder')){add_filter('wp_insert_post_data', 'save_my_nofollow' );}
So I'm setting a filter when either of these options are set, to the function below. My question is, how do I alter the function so that if (2) is set but not (1) I only add nofollow to links matching the target folder URL?
function save_my_nofollow($content) {
$my_folder = get_option('my_nofollow_folder');
$matches = array();
preg_match_all('~<a.*>~isU',$content["post_content"],$matches);
for ( $i = 0; $i <= sizeof($matches[0]); $i++){
if ( isset($matches[0][$i]) && (preg_match('~' . $my_folder . '~', $matches[0][$i])
|| !preg_match( '~'.get_bloginfo('url').'~',$matches[0][$i]))){
$result = trim($matches[0][$i],">");
$result .= ' rel="nofollow">';
$content["post_content"] = str_replace($matches[0][$i], $result, $content["post_content"]);
}
}
return $content;
}
UPDATED code with best answer:
if(get_option('rseo_nofollow')
|| get_option('rseo_nofollow_folder')){
add_filter('wp_insert_post_data', 'save_rseo_nofollow' );
}
function save_rseo_nofollow($content) {
$folder = get_option('rseo_nofollow_folder');
$externalNoFollow = get_option('rseo_nofollow_external');
$folderNoFollow = get_option('rseo_nofollow_folder');
$extRegex = '~'.preg_quote(get_bloginfo('url'), '~') . '~i';
$intRegex = '~'.preg_quote($folder, '~') . '~i';
$dom = new DomDocument();
libxml_use_internal_errors(true);
$dom->loadXml('<root>' . $content['post_content'] . '</root>');
$links = $dom->getElementsByTagName('a');
foreach ($links as $link) {
$href = $link->getAttribute('href');
if ($href && $externalNoFollow && !preg_match($extRegex, $href)) {
$link->setAttribute('rel', 'nofollow');
} elseif ($href && $folderNoFollow && preg_match($intRegex, $href)) {
$link->setAttribute('rel', 'nofollow');
}
}
// print $dom->saveXml();die;
//Since we want to strip the root element, we must do so:
$newContent = '';
$root = $dom->getElementsByTagName('root')->item(0);
foreach ($root->childNodes as $child) {
$newContent .= $dom->saveXml($child);
}
$content['post_content'] = $newContent;
return $content;
}
Input
This is the <a href="http://cnn.com">test</a>. This is the test.
Output
This is the <a rel="nofollow" href=""http://cnn.com"">test</a>. This is the test.