Exclude Custom Post Types From WordPress Search

Feb 14, 2018

Exclude Custom Post Types From WordPress Search


This post was originally created on our sister site WP Cover.
View Original Article
February 14, 2018

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!

The post Exclude Custom Post Types From WordPress Search appeared first on WP Cover.

Additional News

Perfect!

Let's get started. Fill out the form below to email us or request a call back.