My website has a custom post type. I'd like to allow users the ability to search within the custom post type. So I'd like the search results to only include posts of that particular post type.
I'd like to also offer normal search. That is, I'd like the site to have forms that have the standard wordpress search, allowing users the ability to search within the native post types (Post and Page).
Because I want to offer a normal search alongside a customised search, I can't filter the search query with the 'pre_get_posts' hook. So the best option is to custom the search form.
for the post type mypost
with the slug myposts
, I have this form:
<form role="search" method="get"
id="searchform block"
class="search-form"
action="<?php echo esc_url(home_url('/')); ?>"
>
<div class="relative">
<label class="screen-reader-text" for="s"><?php esc_html_e('Search for:', 'text-domain'); ?></label>
<input id="search-field"
type="search"
class="search-field outline-none"
value="<?php echo esc_html(get_search_query()); ?>" name="s" />
<input type="hidden" name="post_type" value="myposts" />
<button class="search-button cursor-pointer absolute right-0 top-0 bottom-0 m-auto py-5 px-4 ml-4" type="submit" id="searchsubmit">
<span class="sr-only"><?php esc_html_e('Search', 'text-domain'); ?></span>
</button>
</div> </form>
In the input parameter value
, I've tried both mypost
and myposts
.
For either value
, a search will return zero results.
Instances of the custom post type do exist.
So: how can I create a working form that will search only for results in the target custom post type?
exclude_from_search
is set tofalse
for your custom post type? This might be helpful: wordpress.stackexchange.com/questions/29447/…