WendiT
WendiT

Reputation: 605

Wordpress: Search results only in one category

I'm using this code for making sure that the search results show only results from one category. It works very well, but the side-effect is that in the back-end on the All posts page a search gives also only results from that same category. How can I make sure it works at the front-end but not the back-end?

//EXCLUDE CATEGORIES FROM SEARCH RESULTS
function SearchFilter($query) {
if ($query->is_search) {
$query->set('cat','1');
}
return $query;
}
add_filter('pre_get_posts','SearchFilter');

Upvotes: 0

Views: 5971

Answers (1)

SidFerreira
SidFerreira

Reputation: 578

Well, this is a common issue and the solution is simple: To avoid this our add_filter should be executed only in frontend. A simple way to do that is using the function is_admin that is a boolean function. So:

function SearchFilter($query) {
  if ($query->is_search) {
    $query->set('cat','1');
  }
  return $query;
}
if(!is_admin())
  add_filter('pre_get_posts','SearchFilter');

Is that it?

Upvotes: 9

Related Questions