Exclude Pages or Posts of Certain Categories from WordPress Search Result

Often, WordPress users need only their posts that appear in the search results. But, by default, WordPress displays posts and pages when site visitor use search feature. If You want to hide the page from the search result, here’s a simple code to do the task.

Exclude Pages or Posts of Certain Categories from WordPress Search Result

Open your function.php and put this code there

function searchExcludePages($query) {
	if ($query->is_search) {
		$query->set('post_type', 'post');
	}

	return $query;
}

add_filter('pre_get_posts','searchExcludePages');

You can also exclude post from certain categories this colde

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

	return $query;
}

add_filter('pre_get_posts','searchExcludePages');

By the code, the pages, and posts from category with ID 2 and 5, wont appear in your WordPress search result.

Source : Excluding Pages from WordPress Search

3 Comments to “Exclude Pages or Posts of Certain Categories from WordPress Search Result”

Add Comments (+)

  1. James says:

    Works great!! Thank you very much.

  2. jlapitan says:

    how can i exclude a page?

  3. elletis1 says:

    check this . . ..   http://webgeek.elletis.com/

Trackbacks/Pingbacks

  1. 40 Best WordPress Tips and Tutorials of December 2010
  2. How to Order Categories by Most Recently Updated

Leave a Reply

 

Amazingly Beautiful WordPress Themes