WordPress Snippets at WPcustoms

Search only in custom post types

Limit the search query to a custom post type with this small snippet. We use the pre_get_posts filter again to jump into the search query and limit it via the conditional tag is_search to our search results only.


/**
 * Snippet Name: Search only in custom post types
 * Snippet URL: https://wpcustoms.net/snippets/search-custom-post-types/
 */
  function wpc_search_in_custom_post_type($query) {
  $post_type = $_GET['type'];
  if (!$post_type) {
    $post_type = 'movies';
  }
    if ($query->is_search) {
        $query->set('post_type', $post_type);
    };
    return $query;
};

add_filter('pre_get_posts','wpc_search_in_custom_post_type');