无论何时使用该功能get_post_meta()
, 将执行上述查询以获取所有post meta并存储在缓存中。你查询的帖子越多,查询的次数就越多。
为了减少查询的数量,我们应该pre-cache all meta values of all posts 在调用之前的查询中get_post_meta
.
这是从中获取的示例代码a tutorial:
add_filter( \'posts_results\', \'cache_meta_data\', 9999, 2 );
function cache_meta_data( $posts, $object ) {
$posts_to_cache = array();
// this usually makes only sense when we have a bunch of posts
if ( empty( $posts ) || is_wp_error( $posts ) || is_single() || is_page() || count( $posts ) < 3 )
return $posts;
foreach( $posts as $post ) {
if ( isset( $post->ID ) && isset( $post->post_type ) ) {
$posts_to_cache[$post->ID] = 1;
}
}
if ( empty( $posts_to_cache ) )
return $posts;
update_meta_cache( \'post\', array_keys( $posts_to_cache ) );
unset( $posts_to_cache );
return $posts;
}