Skip to content

Instantly share code, notes, and snippets.

@runezero
Created May 25, 2022 14:45
Show Gist options
  • Select an option

  • Save runezero/cae0b60b779257532d119b1a6540d188 to your computer and use it in GitHub Desktop.

Select an option

Save runezero/cae0b60b779257532d119b1a6540d188 to your computer and use it in GitHub Desktop.
[Add sitemap to the Robots file] Add the sitemap to the robots.txt file for SEO #wordpress
add_action('plugins_loaded', function(){
add_filter( 'robots_txt', 'maybe_modify_robots_txt', 20, 2 );
}, 999);
/**
* Modify the robots.txt, if not present
*
* @param string $output The robots.txt output
* @param boolean Whether the site is considered "public".
*
* @return string Robots.txt output
*/
public function maybe_modify_robots_txt($output, $public)
{
// Don't add sitemap to robots.txt if website is in development
if (get_option( 'blog_public' ) === '1') {
// First add sitemap if Yoast is active
if (self::yoast_is_active()) {
if (function_exists('get_sites')) {
foreach (get_sites() AS $site) {
if ($site->public == 1 && $site->deleted == 0) {
$output .= "\nSitemap: ".get_site_url($site->blog_id)."/sitemap_index.xml";
}
}
} else {
$output .= "\nSitemap: ".home_url()."/sitemap_index.xml";
}
}
}
//todo: add custom robots lines
$robots_lines = "";
if (!empty($robots_lines)) {
$output .= "\n\n".$robots_lines;
}
// Check of custom rules
return $output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment