Modifying default WordPress Search Results Functionality

Introduction 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 […]

Common Myths about WordPress as CMS

Introduction

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 .

Solution

Snippet for custom search is added below:

[code language="php"]
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');
[/code]

About Author

Robin Thebe

Digital Strategist based in Sydney.

I am multi disciplined web developer based in Sydney focusing around website design, wordpress development, SEO, SEM and Email Marketing.