Removing specific posts from wp-sitemap.xml in WordPress

Looking to remove specific posts from your wp-sitemap.xml file? Here’s a quick and easy guide on how to remove them.

Excluding specific posts from wp-sitemap.xml

In order to exclude specific posts in your wp-sitemap.xml file, you need to add the code below into your theme's functions.php file.

function remove_posts_from_sitemap( $args, $post_type ) {
     if ( 'post' !== $post_type ) {
          return $args;
     }
     $args['post__not_in'] = isset( $args['post__not_in'] ) ? $args['post__not_in'] : array(); $args['post__not_in'][] = 100; // Replace 100 with a specific post's ID
     return $args;
}

add_filter( 'wp_sitemaps_posts_query_args', 'remove_posts_from_sitemap', 10, 2 );