Hello guys i am using following code to make all external links nofollow.
add_filter('the_content', 'my_nofollow');
add_filter('the_excerpt', 'my_nofollow');
function my_nofollow($content) {
return preg_replace_callback('/<a[^>]+/', 'my_nofollow_callback', $content);
}
function my_nofollow_callback($matches) {
$link = $matches[0];
$site_link = get_bloginfo('url');
if (strpos($link, 'rel') === false) {
$link = preg_replace("%(href=\S(?!$site_link))%i", 'rel="nofollow" $1', $link);
} elseif (preg_match("%href=\S(?!$site_link)%i", $link)) {
$link = preg_replace('/rel=\S(?!nofollow)\S*/i', 'rel="nofollow"', $link);
}
return $link;
}
But after adding this code in my site’s Theme Functions all links are still dofollow.
I am using Advanced Custom Fields Pro plugin and links adding by using this plugin are still dofollow.
How to make all external links no follow?
1 Answer
Edit 2: By suggest of @Mark Kaplun, the general solution should be this. We will do filtering after the page is generated, so we won’t care about which plugin we’re using.
We need a hack here to get whole page:
ob_start();
add_action('shutdown', function() {
$final="";
// We'll need to get the number of ob levels we're in, so that we can iterate over each, collecting
// that buffer's output into the final output.
$levels = ob_get_level();
for ($i = 0; $i < $levels; $i++)
{
$final .= ob_get_clean();
}
// Apply any filters to the final output
echo apply_filters('final_output', $final);
}, 0);
I take this code from this question
Then you can remove 2 old filter:
add_filter('the_content', 'my_nofollow');
add_filter('the_excerpt', 'my_nofollow');
Use only one instead:
add_filter('final_output', 'my_nofollow');
Old answer
Just add one more filter.
add_filter('acf/load_value/name=my_field', 'my_nofollow' );
Edit: The concept to solve the problem here is filter the content that generated by plugin, for you here is ACF. Because the_content
is from WP, not the plugin you’re using, so add filter to the_content won’t help.