Content & Posts PHP Beginner

Only Search Blog Posts

Limit your site search to blog posts, so pages like Cart, Checkout or Thank You don't clutter the results.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 10 lines
add_action( 'pre_get_posts', function ( WP_Query $query ): void {
	if ( is_admin() || ! $query->is_main_query() || ! $query->is_search() ) {
		return;
	}

	// Respect a search form that asks for a specific post type, e.g. ?post_type=product.
	if ( ! $query->get( 'post_type' ) ) {
		$query->set( 'post_type', [ 'post' ] );
	}
} );

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.

WordPress search covers posts and pages by default. On most sites that means utility pages, like Cart, My Account or Privacy Policy, show up for common words. This snippet keeps search to blog posts.

How it works

pre_get_posts changes the main search query before it runs, setting post_type to posts only. If a search form already asks for a post type, such as a WooCommerce product search, that’s left alone.

Things to watch

  • To include other types, list them, for example [ 'post', 'product' ].
  • Searches in the admin aren’t affected.

How to test it

Search your site for a word that appears on a page, such as “privacy”. Only posts should 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