Include a custom post type in search results on WordPress

For today’s tutorial, I’m going to show you two ways you can include custom post types on your site’s search results. Custom Post Types aren’t included in results by default, so we need to tweak our theme just a little to make it happen.

Let’s get to it!

Method 1: use a custom function

The first method is the more elegant of the two I’m sharing here, however if this is a little over your head and you’re not comfortable working with PHP, you can use the second method below (although this one’s way better).

Open up your theme’s functions.php file and add the following code, replacing custom_post_type_name with your custom post type’s name:

add_filter( 'pre_get_posts', 'all_cpt_search' );
  function all_cpt_search( $query ) {
  if ( $query->is_search ) {
  $query->set( 'post_type', array( 'post', 'custom_post_type_name' ) );
return $query;

Push your changes and have a look. Your CPT should now be showing in your results!

Method 2: modifying your search form

This option doesn’t involve any coding since all you need to do is basically add a hidden form field to your search form markup where your form appears on your site.

Where your site’s search form appears in your theme files, add the hidden input type markup as seen in this example, replacing custom_post_type_name with your custom post type’s name:

<form action="<?php echo home_url( '/' ); ?>">
  <input type="search" name="s" placeholder="Search">
  <input type="submit" value="Search">
  <input type="hidden" name="post_type" value="custom_post_type_name">

Push your changes and have a look. Again, the first solution is the way to go, but this works, too.

Remember your search results featured images!

Keep in mind that if your search.php template layout includes a featured image thumbnail but your custom post type doesn’t use them, your search results page’s layout may break.

Your template probably looks something like this:

<figure class="featured-image">
  <a href="<?php the_permalink(); ?>">
    <?php the_post_thumbnail(); ?>

Replace it with this, which will display a default image should no thumbnail be available (this applies to all post types in the query, too):

<figure class="featured-image">
 <a href="<?php the_permalink(); ?>">
  <?php if ( has_post_thumbnail() ) {
  } else { ?>
   <img src="<?php bloginfo('template_directory'); ?>/images/default-thumbnail.jpg" alt="<?php the_title(); ?>">
  <?php } ?>

Of course, make sure to create and upload your default image!

Have fun!

Post a comment

Fred looking at his camera phone with a dumb grin on his hairy face About

I'm an Ottawa-based web designer and front end developer who's been in the industry since HTML was written in all-caps with inline CSS. I like writing about the web as well as my other creative interests. Follow me on Twitter


Requests for help are welcome but my schedule means I may be unable to respond right away.