Exclude Pages from WordPress Search Results

Quick WordPress code snippet to remove pages from WordPress search feature.

The native WordPress search feature by default displays pages in the search results. The feature is meant for site-wide searches, but could be annoying to users who just want to display only the posts in the search results.

I have this small code snippet working for me from day one to exclude pages from the searches. It goes in the functions.php file of your WordPress theme:

function search_tweak( $query ) {
  if( $query->is_search ) {
    $query->set( 'post_type', 'post' );
  return $query;
add_filter( 'pre_get_posts', 'search_tweak' );

Save the changed functions.php and make a few searches on your WordPress site. You won’t see any pages in the searches anymore.

If looking for a plugin to do that for you, Simply Exclude may help.