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.
We Recommend
https://kinsta.com › wordpress-hosting
Fast and secure infrastructure, worldwide CDN, edge caching, 35 data centers, and enterprise-level features included in all plans. Free site migrations.
https://gravityforms.com › features
Create custom web forms to capture leads, collect payments, automate your workflows, and build your business online. All without ever leaving WordPress.
Leave a Comment