Created
January 29, 2023 13:30
-
-
Save zarei-dev/8401539a6e791986b13f493b4702eb03 to your computer and use it in GitHub Desktop.
Nofollow all external links inside posts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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