In this article, we will learn how to make your search more relevant and less crowded by excluding pages from WordPress search results or only showing custom post types.

A. Changing the whole site Searching

1. Search Only Blog Post WordPress

if (!is_admin()) {
    function wpb_search_filter($query) {
        if ($query->is_search) {
            $query->set('post_type', 'post');
        }
        return $query;
    }
    add_filter('pre_get_posts', 'wpb_search_filter');
}

2. Search Only Pages in WordPress

if (!is_admin()) {
    function wpb_search_filter($query) {
        if ($query->is_search) {
            $query->set('post_type', 'page');
        }
        return $query;
    }
    add_filter('pre_get_posts', 'wpb_search_filter');
}

3. Search Only Custom Post type WordPress

if (!is_admin()) {
    function wpb_search_filter($query) {
        if ($query->is_search) {
            $query->set('post_type', 'custom_post_type');
        }
        return $query;
    }
    add_filter('pre_get_posts', 'wpb_search_filter');
}
/* Put your post type instead of "custom_post_type" */

B. Changing the Search Widget

add_filter('widget_title', function( $title, $instance, $id_base ) {
  // Target the search base
  if ('search' === $id_base)
  add_filter('get_search_form', 'wpse_post_type_restriction');
  return $title;
}, 10, 3);

function wpse_post_type_restriction($html) {
  // Only run once
  remove_filter(current_filter(), __FUNCTION__);

  // Inject hidden post_type value
  return str_replace(
    '</form>
    ', '<input type="hidden" name="post_type" value="custom_post_type" /></form>
    ', $html
  );
}
/* Put your post type instead of "custom_post_type" */
/* To display only Page put "page" */
/* To display only Blogs put "post" */
There are currently no comments.