Today I want to share with you a quick and easy tutorial on how to exclude pages from WordPress search results.
By default, WordPress will include your site’s pages in its search results. For most websites, this is not necessary or desired. In order to change this behavior, we can add simple function into our functions.php
file in order to filter out those pages in our search results.
The Function to Exclude Pages from WordPress Search Results
Simply copy and paste this function into your functions.php
file of your WordPress theme:
/**
* This function modifies the main WordPress query to remove
* pages from search results.
*
* @param object $query The main WordPress query.
*/
function tg_exclude_pages_from_search_results( $query ) {
if ( $query->is_main_query() && $query->is_search() && ! is_admin() ) {
$query->set( 'post_type', array( 'post' ) );
}
}
add_action( 'pre_get_posts', 'tg_exclude_pages_from_search_results' );
This function does exactly what we need it to do. By modifying the main WordPress query via the pre_get_posts
hook, we can determine what we want to show in our search results. In this case, all we want to show is content from our blog posts, not our pages.
Want a WordPress website that’s secure AND fast? My friends at WP Engine are offering 3 months free on all annual plans. Click here to claim your special WP Engine offer!
And there you have it! Simply save your file and test out a search query. You have excluded pages from your WordPress search results!
Hope you enjoyed the post, and don’t forget to subscribe to get more great WordPress content! Also, check out the follow up post on how to include custom post types in WordPress search results!
The post How to Exclude Pages from WordPress Search Results appeared first on Thomas Griffin.