Tutorials WordPress

WordPress: Search Custom Post Type(s)

Updated

Written by

Dave Warfel

Reading Time

2 minutes

If you buy something from one of our links, we may earn a commission.

I’ll admit, the default WordPress search engine is not the most robust. However, there are a few ways to customize it. One of the most common requests is, “How do you limit a WordPress search to a custom post type?” Below, I explain how to display results for one post type, as well as multiple custom post types.

Limit WordPress Search Results to 1 Custom Post Type

If all you want to do is limit your WordPress search to a single custom post type, add the following line of code inside the <form> on your searchform.php template.

<input type="hidden" name="post_type" value="your-posttype-here" />

Depending on how you have customized your searchform.php template, it should look something like this:

<form id="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>" method="get">
	<input type="hidden" name="post_type" value="your-posttype-here" />
	<label class="assistive-text" for="s">Search</label>
	<input id="s" class="field" type="text" name="s" />
	<input id="searchsubmit" class="submit" type="submit" name="submit" value="Search" />
</form>

Limit WordPress Search Results to Multiple Custom Post Types

If you want to limit your search to more than one custom post type, you have to go about it a slightly different way.

Add the following lines of code in the same place in your searchform.php file:

<input type="hidden" name="post_type[]" value="post_type_one" />
<input type="hidden" name="post_type[]" value="post_type_two" />

Replace post_type_one and post_type_two with the name of your custom post type.

This works mainly because WordPress’ WP_Query object can handle the post_type parameter as an array.

Thanks to John Sparrow for this code snippet.

Dave Warfel

LinkedIn  •  X (Twitter)Dave has been working with WordPress since 2011. He's built 100s of client sites and almost a dozen of his own. He's tested almost every plugin you can think of, hosted with at least 10 different companies, and gone down every SEO rabbit hole you can imagine. When's he's not tinkering with new software, you'll find him in the mountains of Colorado, trail running, summiting peaks, and rippin' downhills on his mountain bike. 🏔️🏃🚴🤸

Leave a Comment