Back WordPress

How to Display Specific Category Only In Search Result

WRITTEN BY ON 04 May 2011
15,832 VIEWS • SHARES
2 comments

While customizing a WordPress site, sometimes We also need to configure, how our WordPress site display the search result. On our previous code snippet, I have showed how to exclude specific category from search result. This tutorial will be the reserve, display the posts from specific category only in search result.

PHP

Simply insert the code to function.php file in your theme folder.
This code will only show post from category with ID 2 and 5 in search result

function searchcategory($query) {
	if ($query->is_search) {
		$query->set('cat','2,5');
	}

	return $query;
}

add_filter('pre_get_posts','searchcategory');

Join the discussion

Comments will be moderated and rel="nofollow" will be added to all links. You can wrap your coding with [code][/code] to make use of built-in syntax highlighter.

2 comments
Don Banz 12 years ago
I have a few questions about this code:

1) If implement this is it going to affect the search globally on my site?-I ask this because I only need it to function like this for a particular area.

2) How can I get this to work for tags? (is it just a matter of swapping 'cat' for 'tag'?)

3) Once I have it working for tags, I need it work based off of page slug meaning that the tag would be the same as the current page slug. Is this possible?
Reply
Lucena 12 years ago
yup how can i use it in tag search? i use your code in my site in http://www.lucenahin.com.ph its search the specific category but i cant use in tag search
Reply