deepak-rajpal
11/20/2015 - 2:18 PM

WordPress Search Filter

WordPress Search Filter

<?php
// Preventing Global Search from custom post types
// Filter only if it is not application search, checked using cat variable
function searchfilter($query) {
    if ($query->is_search && !is_admin() && !isset($_REQUEST['cat']) && $_REQUEST['cat'] != 'applications') {
        $query->set('post_type',array('post','page'));
    }
return $query;
}
add_filter('pre_get_posts','searchfilter');
?>
<?php
/* When we search without string/word, it redirects to homepage. Fix it by checking this empty case and set query variable with space " " */
function empty_search_filter( $query_vars ) {
    if( isset( $_GET['s'] ) && empty( $_GET['s'] ) ) {
        $query_vars['s'] = " ";
    }
    return $query_vars;
}
add_filter( 'request', 'empty_search_filter' );
?>