Common Myths about WordPress as CMS

Modifying default WordPress Search Results Functionality

WordPress by default searches all the content including pages, posts etc. This might result to displaying unwanted content in search results which might make look website functions clunky and not appealing. In turn isn’t good for user experience too.

Often during the process of custom wordpress development, there might be cases where you want to limit the search results to a specific post type or only pages or even custom posts or to a combination of pages and posts etc.

Fortunately wordpress provide an easy way to implement custom search, by overriding core hook pre_get_posts .

Snippet for custom search is added below:

function wp_guru_filter($query) {
  if ( !is_admin() && $query->is_main_query() ) {
    if ($query->is_search) {
      $query->set('post_type', array( 'post', 'services' ) ); // includes post, and custom post services
    }
  }
}

add_action('pre_get_posts','wp_guru_filter');

About Author

I am Robin - WordPress Developer based in Sydney. I work as Digital Developer. I do some projects now and then, and love blogging about WordPress and Web Design.