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 *

Your post must include a link to this post.

How does this work?
Write a response on your own website and include a link to this post. Then submit your response’s URL here. Your response may appear here after moderation. To update or remove it, edit or delete your original post and submit the same URL again. Learn more about Webmentions.