Skip to content

Backgrounds

How-to Guides

Technical References

Enterprise Search /

Identify which post meta are indexed

This is the third step in the audit we discussed in the introduction: post meta.

Post meta must be indexed to be used in queries

If a post meta is not explicitly indexed, a search will return an error that the meta was not found; the search will fail until the meta key is added to the allow list.

Keep in mind that some post meta may be used only for displaying information; others may be used for tracking things, and some may be used as part of a search. Only the post meta that is being searched or queried needs to be indexed.

To display post meta, your theme code should access the meta using WordPress functions, and not rely on the Elasticsearch (ES) search results for that field.

Using our events example, you have code that is filtering by events starting today. The section of query filter code includes:

$args = array(
	'post_type'      => 'event',
	'post_status'    => 'publish',
	'posts_per_page' => 30,
	'meta_query' => array(
		array(
			'key'     => 'event-start-date',
			'value'   => strtotime( 'today' ),
			'type'    => 'string',
			'compare' => '>=',
		),
	),
);
$query = new WP_Query( $args );	 

In the code above, the relevant post meta we need to index is event-start-date.

Adding post meta to an allow list

To index the event’s start date meta, but only for posts of type event, you’ll use this filter:

add_filter( 'vip_search_post_meta_allow_list', 'mysite_events_indexable_post_meta', 10, 2 );

function mysite_events_indexable_post_meta( $allow, $post ) {
	If ( is_object( $post ) && 'event' === $post->post_type ) {
		$allow['event-start-date'] = true;
	}

	return $allow;
}

Adding post meta regardless of post type

The allow list filter also supports enabling post meta regardless of post type. We support calling the filter without a WP_Post object as the second parameter, so you could quickly enumerate the post meta that are supported globally.

Note that if one post type uses the meta and you do not want that post type’s meta indexed, you will still need to inspect the $post filter parameter and should not enable that post meta globally.

add_filter( 'vip_search_post_meta_allow_list', 'mysite_global_indexable_post_meta', 10, 2 );

function mysite_global_indexable_post_meta( $allow, $post = null ) {
	$allow['hide-from-homepage'] = true;

	return $allow;
}

Note the convention here builds a list that looks as follows; this permits later filters to disable items by changing the value to something other than true:

[
	'event-start-date' => true,
	'event-end-date'   => true,
]

Note

It’s important to be consistent for each allow list, but also to be aware of the format differences between the three allow lists.

Last updated: May 25, 2021