As a seasoned WordPress developer with years of experience optimizing sites for performance and usability, I've relied on this technique countless times to refine search functionality. If you've ever wanted to limit search results to specific post types—like posts and pages only—it's a simple tweak using your theme's functions.php file. This builds on methods like disabling search entirely, but focuses on precise filtering.
Open your child theme's functions.php file (always use a child theme to prevent losing changes during updates) and add this proven code snippet:
function searchfilter( $query ) {
if ( $query->is_search && ! is_admin() ) {
$query->set( 'post_type', array( 'post', 'page' ) );
}
return $query;
}
add_filter( 'pre_get_posts', 'searchfilter' );Pay close attention to this key line:
$query->set( 'post_type', array( 'post', 'page' ) );Customize the array values to target other post types, such as 'product' for WooCommerce or 'portfolio' for custom content. This ensures your search delivers relevant results, enhancing user experience and site authority.