If you’re using a lot of custom post types, your search results page could have content you don’t want in it. One solution is to set
'exclude_from_search' => true when registering your post type (more info).
But what if you don’t want to exclude them from all searches – just one specific search? I recently created a Videos section for a client site that pulls in content from the custom post type ‘video’. We wanted a search box on that page that specifically searched through the video post type.
WordPress lets you specify a post type (or multiple post types) by using a hidden field in your search form.
You could use the
get_search_form filter to rebuild the search form in that specific context, but here’s a simpler approach:
|// The standard search form|
|$form = get_search_form( false );|
|// Let's add a hidden input field|
|$form = str_replace( '<input type="submit"', '<input type="hidden" name="post_type" value="video"><input type="submit"', $form );|
|// Display our modified form|
I know that the search form will include a submit button, so I’m sticking the hidden input in front of that by doing a find/replace.