Skip to content

Indexing post meta

Post meta is not indexed by default; if it is not explicitly defined in the allow list, it will not be indexed.

Adding post meta to the allow list

Use the vip_search_post_meta_allow_list to customize which post meta is to be indexed.

There are many kinds of post meta — some may be used only for displaying information, others may be used for tracking things, and some may be used as part of a search. For example, if we want to index the hide-from-homepage post meta:

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 false:

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

Note

Once the post meta allow list has been modified, re-indexing will be required.

Another example where if you wanted to index the post meta of event-start-date only for event post types, use the second $post parameter:

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;
}

Post meta must be indexed to be used in queries

If a post meta is not indexed, a search will return an error that the meta was not found and will fail until the meta key is added to the allow list. To display post meta, your code should access the meta using WordPress functions, and not rely on the Elasticsearch (ES) search results for that field.

For example, using a meta query on event post types with a publish status, the post meta we would need to index is event-start-date:

$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 );	 

Last updated: April 03, 2023

Relevant to

  • WordPress