Skip to content

Instantly share code, notes, and snippets.

@zarei-dev
Created January 29, 2023 13:30
Show Gist options
  • Save zarei-dev/8401539a6e791986b13f493b4702eb03 to your computer and use it in GitHub Desktop.
Save zarei-dev/8401539a6e791986b13f493b4702eb03 to your computer and use it in GitHub Desktop.
Nofollow all external links inside posts
<?php
// nofollow all external links in posts and pages
add_filter('the_content', 'vc_nofollow');
add_filter('the_excerpt', 'vc_nofollow');
function vc_nofollow($content) {
return preg_replace_callback('/<a[^>]+/', 'vc_nofollow_callback', $content);
}
function vc_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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment