SEO PHP Beginner

Exclude Specific Posts From the Sitemap

Leave individual posts or pages, such as a thank-you page or a landing page for ads, out of the WordPress sitemap.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 7 lines
add_filter( 'wp_sitemaps_posts_query_args', function ( array $args, string $post_type ): array {
	// IDs of posts and pages to leave out.
	$exclude = [ 42, 108 ];

	$args['post__not_in'] = array_merge( $args['post__not_in'] ?? [], $exclude );
	return $args;
}, 10, 2 );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

Thank-you pages, ad landing pages and members-only pages don’t belong in your sitemap. This snippet leaves them out by ID.

How it works

WordPress builds each post type’s sitemap with a database query. The wp_sitemaps_posts_query_args filter lets you change that query; adding IDs to post__not_in leaves those posts out, whatever their type.

Things to watch

  • Find a post’s ID in the URL when editing it (post.php?post=42), or use the snippet that shows IDs in admin lists.
  • Pair it with the snippet that noindexes specific pages, so the pages don’t show in search results either.

How to test it

Open the page sitemap at /wp-sitemap-posts-page-1.xml. The excluded page shouldn’t be listed.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only