Add Rules to the Virtual robots.txt
Adds Disallow rules for internal search result URLs to the robots.txt file that WordPress generates.
Opens WPIDE on
Code
add_filter( 'robots_txt', function ( $output, $public ) {
if ( ! $public ) {
return $output;
}
$rules = "Disallow: /?s=\nDisallow: /search/\n";
if ( false !== strpos( $output, "User-agent: *\n" ) ) {
return preg_replace( '/User-agent: \*\n/', "User-agent: *\n" . $rules, $output, 1 );
}
return "User-agent: *\n" . $rules . "\n" . $output;
}, 10, 2 );
Notes
Only works when there is no physical robots.txt file in the site root.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.