relevanssi_get_post_meta_for_all_posts()

relevanssi_get_post_meta_for_all_posts( array $post_ids, string $field )

This function fetches a post meta field for many posts with one database query.

Parameters

$post_ids
(array) An array of post IDs.

$field
(string) The name of the custom field to fetch.

More information

Note that this only works for custom fields with only one value per post.

If you want to use custom field content in search result filtering, calling get_post_meta() to fetch the custom field values is convenient but expensive. Each get_post_meta() call is a database query; if your search returns 300 results, that’s 300 database queries.

Fetching the custom fields for all posts with one database query is more effective. You can use this function to do that.

For example, this is a simple way to add a boost for posts with the “featured” custom field set to 1:

add_filter( 'relevanssi_match', 'custom_field_weights' );
function custom_field_weights( $match ) {
	$featured = get_post_meta( $match->doc, 'featured', true );
	if ( '1' === $featured ) {
 		$match->weight = $match->weight * 2;
	}
	return $match;
}

However, it’s more effective to do it this way:

add_filter( 'relevanssi_results', 'custom_field_weights' );
function custom_field_weights( $results ) {
    $featured = relevanssi_get_post_meta_for_all_posts( array_keys( $results ), 'radio_button_field_button_link', true );
    array_walk(
        $featured,
        function( $value, $post_id ) use ( &$results ) {
            if ( 1 === (int) $value ) {
                $results[ $post_id ] *= 2;
            }
        }
    );
    return $results;
}

First, this uses relevanssi_results instead of relevanssi_match to trigger this only once per post (relevanssi_match triggers once per matching term, which leads to uneven boosts). Second, this does only one database query instead of at least one per post.