Skip to content

Instantly share code, notes, and snippets.

@deepak-rajpal
Created November 20, 2015 14:18
Show Gist options
  • Save deepak-rajpal/ee77e083204ffe2f7ad3 to your computer and use it in GitHub Desktop.
Save deepak-rajpal/ee77e083204ffe2f7ad3 to your computer and use it in GitHub Desktop.
WordPress Search Filter
<?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' );
?>
<?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');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment