Include custom post types in the search using WordPress hooks

To include custom post types in the default search, we need to modify the search function using an action hook. Post types that we want to search through are added to the search query in an array. The array needs to include WordPress’s default post & page types as this function does not append post types to the default search.

Paste the following code into your theme’s functions.php file.

1
2
3
4
5
6
7
8
// this example adds the 'service' and 'product' CPTs to the search function. Change the CPT name as required.
function search_custom_post_types( $query ) {
    if ( $query->is_main_query() && $query->is_search() && ! is_admin() ) {
        $query->set( 'post_type', [ 'post', 'page', 'service', 'product' ] );
    }
}
add_action( 'pre_get_posts', 'search_custom_post_types' );