By default, performing a search on a WordPress website will search through everything; all pages, posts, and any custom posts types that have been created. I came across a scenario earlier however where I wanted to exclude pages from the search and filter the results by multiple custom post types.
To be honest I struggled to find the solution immediately so wanted to explain how you can filter by one or more post types. For both of the explanations below I will explain how this can be achieved by editing the search form, or by editing the themes functions.php file.
Note: For information on creating a search form see this link:
http://codex.wordpress.org/Function_Reference/get_search_form
Filter Search Results by a Single Post Type
Search Form
<form method="get" id="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>"> <input type="text" class="field" name="s" id="s"> <input type="hidden" class="field" name="post_type" id="post_type" value="movies"> <input type="submit" class="submit" name="submit" id="searchsubmit" value="<?php esc_attr_e( 'Search' ); ?>"> </form>
functions.php
function SearchFilter($query) { if ($query->is_search) { $query->set('post_type', 'movies'); } return $query; } add_filter('pre_get_posts', 'SearchFilter');
Filter Search Results by Multiple Post Types
Search Form
<form method="get" id="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>"> <input type="text" class="field" name="s" id="s"> <input type="hidden" class="field" name="post_type[]" id="post_type" value="movies"> <input type="hidden" class="field" name="post_type[]" id="post_type" value="photos"> <input type="submit" class="submit" name="submit" id="searchsubmit" value="<?php esc_attr_e( 'Search' ); ?>"> </form>
functions.php
function SearchFilter($query) { if ($query->is_search) { $query->set('post_type', array('movies', 'photos')); } return $query; } add_filter('pre_get_posts', 'SearchFilter');
So there we have it. By using an array we can filter the search results by two or more post types.