How to Include Custom Post Types in WordPress Search Result

Since WordPress 3.0 You can Create your own custom post types.By Default WordPress Include only posts and pages post types.So in this tutorial you will learn how to include Custom post types in WordPress Search Result.

Go to your WordPress Theme functions.php file or your plugin file and Add the following code.

function add_custom_types_in_search_result( $query ) {
  if( is_search() && $query->is_main_query()) {
    $query->set( 'post_type', array(
     'post', 'your-custom-post-type-here'  //Replace your-custom-post-type-here to your custom post types
        ));
      return $query;
    }
}

If you wants to include all Custom post types in your wordpress search Result then use this code.

function add_custom_types_in_search_result($query) {
	if(is_search() && $query->is_main_query()) {
		$post_types = get_post_types(array('public' => true, 'exclude_from_search' => false), 'objects');
		$searchable_types = array();
		if($post_types) {
			foreach( $post_types as $type) {
				$searchable_types[] = $type->name;
			}
		}
		$query->set('post_type', $searchable_types);
	}
	return $query;
}
add_filter( 'pre_get_posts', 'add_custom_types_in_search_result' );

I would like to hear your feedback through Comment and please do not forget to share with your friends.

Shubham Kumar

Hey, I am Shubham and i love Blogging, Coding and exploring new things and obviously sharing my experience with you.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *