Exclude pages from WordPress Search Correctly

I was searching last night for a way to easily remove everything except for my blog posts from the WordPress search. After looking through a few articles on editing the loop and using query_posts function to change the query, I found what I was looking for. Only to find out the example didn’t work.

The article was on wpbeginner, which is a reputable site that I do refer to often when I am looking for a quick fix. After looking into the code this morning I realized one core flaw. The article I was reading was using add_filter instead of add_action. After doing my research, I realized that there is no pre_get_posts filter and chnage the code to what is below:

function js_search_filter( $query ) { if ( $query->is_search ) { $query->set('post_type', 'post'); } return $query; } add_action( 'pre_get_posts', 'js_search_filter' );

Now that code works, just place this snippet inside of your functions.php file in the root of your theme folder. This will change your search prams from any post-type to only posts. If will ignorel pages, custom post-types, etc.