Excluding Post Types from being Indexed

There could be a couple of reasons why you may want to exclude certain post types entirely from being indexed by ElasticPress and some of the most important ones are below.

  • Prioritizing relevant content: You may have a particular post type that hosts information that is useful but not relevant for search results. Examples are administrative content that is publicly available but is for internal use, internal guides, tutorials, or documentation for staff or developers, which are useful for the intended audience but not relevant to the general public.
  • Reducing Elasticsearch resource consumption: If you are using ElasticPress.io, our managed Elasticsearch service, it is quite important to make your website index as efficient as possible by differentiating the content that’s publicly available and searchable especially since your ElasticPress plan has a limited number of documents that can be indexable. Excluding post types is another way to guarantee that you are only indexing posts that are relevant to the results a user is supposed to see.
  • Complying with data privacy regulations: Excluding specific post types may be necessary to comply with data privacy regulations like GDPR, CCPA, or other regional requirements. Certain post types may store sensitive user information that should not be indexed or searchable. Excluding these post types can help you meet compliance requirements and protect your users’ data.

The snippet below allows you to exclude the product post type:

PHP
/**
 * Exclude post types from indexing
 *
 * @param array $post_types
 * @return array
 */
function exclude_post_types_from_indexing( $post_types ) {
	unset( $post_types['product'] );

	return $post_types;
}
add_filter( 'ep_indexable_post_types', 'exclude_post_types_from_indexing' );

Inside the function, the unset() function removes the 'product' post type from the $post_types array. If the 'product' post type exists in the array, it will be removed.

In order to exclude multiple post types, we can create an array containing the post types we want to exclude. We then loop through the array and remove each post type from the main $post_types array using the unset() function as seen below.

PHP
/**
 * Exclude post types from indexing
 *
 * @param array $post_types
 * @return array
 */
function exclude_post_types_from_indexing( $post_types ) {
	// Post types to exclude
	$exclude_post_types = [ 'product', 'teams', 'reports' ];

	// Loop through the post types to exclude
	foreach ( $exclude_post_types as $exclude_post_type ) {
		if ( isset( $post_types[ $exclude_post_type ] ) ) {
			unset( $post_types[ $exclude_post_type ] );
		}
	}

	return $post_types;
}
add_filter( 'ep_indexable_post_types', 'exclude_post_types_from_indexing' );

This snippet excludes the product, teams, and reports post type as an example. To add the above snippets to your ElasticPress installation, follow the guide available here.