Skip to content

Indexing post meta

Post meta is not indexed by default. If post meta 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 different types of post meta. Some types of post meta might be used only for displaying information. Other types might be used for tracking things, and some may be used as part of a search. In this code example, the hide-from-home-page post meta is added to the allow list and indexed:

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-home-page'] = 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

After the post meta allow list has been modified, re-indexing must be performed.

This code example demonstrates how to index the post meta of event-start-date, but only for event custom post types. The post type is passed to the $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, 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 that must be indexed 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: December 22, 2023

Relevant to

  • WordPress