Exclude Custom Post Types From WordPress Search


About The Author
Cabe Nolan is the founder of WP Cover where he shares his insight into WordPress, development, & entrepreneurship. Outside of WPCover, Cabe continues to run a successful WordPress development firm, Bold City Design as well as a few high profile websites, Arrivala, Two Way Resume, Dock Skipper, and a successful outdoors brand, DolfinPack.







Exclude Custom Post Types From WordPress Search

Ready for your quick code snippet this week?  Here it is:

I’ve been working a lot with custom website backends.  In summary, this creates three separate aspects to the site.  You have:

  • WordPress Admin (wp-admin)
  • Website User Admin
  • Frontend Of Site

 
When creating these setups, I often have the need to create custom post types that are used for storing data but should not be shown on the site.  One thing that slips many developers minds, is the need to exclude these from the default search, and luckily it is easy:

 

function wpcover_filter_search($query) {
	if (!$query->is_admin && $query->is_search) {
		$query->set('post_type', array('post', 'programs', 'resource'));
	}
	return $query;
}
add_filter('pre_get_posts', 'wpcover_filter_search');

 

What we’re doing here is modifying the WordPress default search query to only look within the post types of ‘post’, ‘programs’, or ‘resource. You would want to modify these based on the post types on your custom site and what you want to be searchable.

There’s your quick code snippet of the week!


Share Your Thoughts

Leave a Reply

Your email address will not be published.


Related Stuff You Might Like







WordPress News, Tips, & Code Snippets

Join the WP Cover mailing list and get wordpress news, tips, code snippets, security warnings, and more delivered right to your inbox.  We won't flood your inbox, newsletters typically go out every 1-2 weeks unless it involves an important security release.

You have Successfully Subscribed!