/**
* Exclude pages from WordPress search results
*/
function custom_exclude_pages_from_search( $query ) {
if ( ! is_admin() && $query->is_main_query() && $query->is_search() ) {
$query->set( ‘post_type’, ‘post’ );
}
}
add_action( ‘pre_get_posts’, ‘custom_exclude_pages_from_search’ );
Steps
1. Add the PHP code to your theme's functions.php file or a PHP snippets plugin.
2. Save and activate the snippet.
3. Search for a keyword on your website.
4. Only blog posts will appear in the search results.
Tested on
WordPress 6.8
Reported by the author on November 16, 2026. WPFolks has not verified this.
Not tested against WordPress 7.1.5. It may still work.
