_prime_post_caches()WP 3.4.0

Adds any posts from the given IDs to the cache that do not already exist in cache

This is an internal function for using it by WP core itself. It's not recommended to use this function in your code.

1 time — 0.012805 sec (extremely slow) | 50000 times — 0.78 sec (very fast)

No Hooks.

Return

null. Nothing.

Usage

_prime_post_caches( $ids, $update_term_cache, $update_meta_cache );
$ids(int[]) (required)
ID list.
$update_term_cache(true|false)
Whether to update the term cache.
Default: true
$update_meta_cache(true|false)
Whether to update the meta cache.
Default: true

Examples

0

#1 Add the posts to the cache when processing comments

An example from the core function get_comments().

// Prime comment post caches.
if ( $this->query_vars['update_comment_post_cache'] ) {

	$comment_post_ids = array();

	foreach ( $_comments as $_comment ) {
		$comment_post_ids[] = $_comment->comment_post_ID;
	}

	_prime_post_caches( $comment_post_ids, false, false );
}
0

#2 Add the posts to the cache when we get the posts

An example from the core function get_posts().

$ids = $wpdb->get_col( $this->request );

if ( $ids ) {
	$this->posts = $ids;
	$this->set_found_posts( $q, $limits );
	_prime_post_caches( $ids, $q['update_post_term_cache'], $q['update_post_meta_cache'] );
} else {
	$this->posts = array();
}

Notes

Changelog

Since 3.4.0 Introduced.
Since 6.1.0 This function is no longer marked as "private".

_prime_post_caches() code WP 6.1.1

function _prime_post_caches( $ids, $update_term_cache = true, $update_meta_cache = true ) {
	global $wpdb;

	$non_cached_ids = _get_non_cached_ids( $ids, 'posts' );
	if ( ! empty( $non_cached_ids ) ) {
		$fresh_posts = $wpdb->get_results( sprintf( "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE ID IN (%s)", implode( ',', $non_cached_ids ) ) );

		update_post_caches( $fresh_posts, 'any', $update_term_cache, $update_meta_cache );
	}
}