Custom post type in the search results

All WordPress themes include posts into search results, some of them also contain pages. We want to see our custom post type in the search results, ex. “book”.

To do that we need to add a piece of code to a functions.php file located into our theme root directory.

add_action( 'pre_get_posts', 'wpi_cpt_search' );
if ( ! function_exists( 'wpi_cpt_search' ) ) {
    function wpi_cpt_search( $query ) {
        if ( ! is_admin() && is_search() && $query->is_search ) {
            $query->set( 'post_type', array( 'post', 'page', 'book', 'member', 'teacher' ) );
        return $query;

We are adding action to pre_get_posts hook. Our function adds posts, pages and also our custom post types: book, member and teacher.

Before we modify query there is also checking:

  • if no dashboard view is being displayed
  • result page archive is being presented
  • is the query for a search

After we match all of these conditions, our query is modified and we can also search for custom post types: books, members or teacher.

If you want to check how to add custom post type please take a look here.

Share this post
  • 1

Leave a Reply

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