WordPress search: only show post and not pages

This tip is a quick one but something asked for regularly. By default the WordPress will show both posts and pages in the results.

If you’d rather just show posts and you use the Thesis framework, just place the code below in your custom_functions.php file and you’re done!

<?php
function SearchFilter($query) {
if ($query->is_search) {
$query->set('post_type', 'post');
}
return $query;
}
add_filter('pre_get_posts','SearchFilter');
?>

Here’s an updated version of this that fixes the search when you’re in the administration screen, basically leaving that to it’s default behaviour when your logged in.

The other thing I’ve added to this is the ability to place a hidden form field in a search form then use this if statement to test if we want to search just with in a custom post type, in this case one called organisations.

function SearchFilter($query) {
if ($query->is_search && !is_admin()) {

	// are we wanting to search Custom posts?
	if ($_GET['bsearch'] =="yes"){
			$query->set('post_type', 'organisations');
	}
	else{
			//default behavour we want is to search posts only
			$query->set('post_type', 'post');
	}


}
return $query;
}

add_filter('pre_get_posts','SearchFilter');

Say Hello!

Got a WordPress or Digital Marketing Project that you'd like to discuss? I'm interested in hearing about new projects and where I might be able to assist. Please visit contact page here.
  • http://thriveweb.com.au Dean

    Ah… Post only works great, thank you!

    • Peter

      Glad it helped!

  • Pingback: Code snipits to help ‘CMS’ your WordPress sites › Gold Coast Web Design › WordPress websites, support and hosting › THRIVE

  • http://cicsc.org.bo/2011/01/17/enero-2011-plan-de-marketing/ Danielle

    It’s remarkable to go to see this web page and reading the views of all friends about this post, while I am also eager of getting experience.

  • Bun Chhourng Bmc

    thank!

  • Joel Farris

    “place a hidden form field in a search form then use this if statement to test if we want to search just with in a custom post type”

    Can you offer additional instruction on how to get this working? What hidden field do I need to add to trigger it?

    • Joel Farris

      Nevermind, figured it out. Thanks!