Add custom post types to WordPress search

Add RSS feed to Reader and sync to Readwise.

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:

// 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' );
Code language: PHP (php)

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *