cafe_prime_fields()
Purpose
Loads the CAFE data of many objects at once: values, and when needed Collection / Section Builder rows, Gallery relationships and attachments. Reading their fields afterwards with the normal APIs runs no further query per object. This avoids the "N+1" problem in loops. Guide: Performance.
Syntax
cafe_prime_fields( mixed $object_ids, array $fields = [], ?string $object_type = null ): int
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
$object_ids |
mixed | - | One object reference or a list: post IDs, WP_Post, WP_Term, WP_User or WP_Comment objects, or 'option' for Settings Page values. |
$fields |
string[] |
[] |
Names or keys of the fields you will read. They decide whether rows, relationships and media are loaded too. Empty loads everything. Unknown names are ignored. |
$object_type |
string|null | null |
Type of plain IDs: 'post' (default), 'term', 'user' or 'comment'. |
Return value
The number of objects whose values were loaded from the database. Objects
already in request memory or in the object cache do not count, so 0 means
everything was already available.
Example
$ids = get_posts(
[
'post_type' => 'product',
'posts_per_page' => 500,
'fields' => 'ids',
]
);
cafe_prime_fields( $ids, [ 'price', 'gallery', 'specifications' ] );
foreach ( $ids as $id ) {
$price = cafe_get_field( 'price', $id );
foreach ( cafe_rows( 'specifications', $id ) as $spec ) {
echo esc_html( $spec['label'] . ': ' . $spec['value'] );
}
}
// Terms and Settings Page values.
cafe_prime_fields( $term_ids, [ 'color' ], 'term' );
cafe_prime_fields( 'option' );
Notes
- Loads with one set-based query per kind of data (
object_id IN (…), 500 IDs per query) for everything not already cached. The object cache is read with one multi-get. - Values are loaded for all fields of the objects (one query either way), which keeps CAFE's per-object cache complete.
WP_Queryloops andget_terms()results are batched automatically; you only need this function for ID lists,get_posts()and users or comments.- Saving or deleting a value after priming is seen immediately.
- Sensitive values (Password) are never written to the object cache.