Exclude posts from WordPress’s Sitemap

Starting with 5.5, WordPress now generates its own sitemap.xml without the need of a plugin. It’s possible to filter the results to exclude a specific post using the below filter:

function remove_page_from_sitemap ($args, $post_type ) {
    if ($post_type === "page") {
        $posts_not_in = [ 1234 ];
        
        if ( isset($args['post__not_in']) ) {
            $posts_not_in = array_merge( $posts_not_in, $args['post__not_in'] );
        }

        $args['post__not_in'] = $posts_not_in;
    }

    return $args;
}

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

That filter takes a familiar WP_Query argument, so it’s quite simple to add any additional filters, for example if you wanted to exclude posts from a specific term or from specific authors, using any existing WP_Query parameters.


Leave a Reply

Your email address will not be published. Required fields are marked *

To respond on your own website, enter the URL of your response which should contain a link to this post’s permalink URL. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post’s URL again. (Find out more about Webmentions.)