wordpress的WP_Query类相关缓存参数及函数

WordPress教程 1490

前面博客吧整理了wordpress的WP_Query类使用方法和所有参数,其中有几个用于缓存相关的参数和函数,分别是cache_resultsupdate_post_term_cacheupdate_post_meta_cacheupdate_post_caches以及lazy_load_term_meta,下面对其分别进行介绍说明。

cache_results

是否缓存查询的文章信息。

默认情况分两种,使用外部对象缓存(比如使用 Memcached)就是false,没有使用则是true。

做了几次测试,true和false没什么区别,感觉有点重复,所以这个建议设置为false。

update_post_term_cache参数

是否缓存post term的内容,默认也是true。

update_post_term_cache开启之后,在列表页使用get_the_terms函数的时候,不需要导数据里面去请求每个post的各种taxonomy的term的信息,它会把整个列表所有文章的所有taxonomy的term一起全部请求出来。

update_post_meta_cache 参数

是否缓存post meta的内容,默认是 true。

update_post_meta_cache开启之后,在列表页使用get_post_meta函数的时候,不需要导数据里面去请求每个post_id的post meta的信息,它会把整个列表所有文章的post meta一起全部请求出来。

update_post_caches 函数

WordPress会使用_prime_post_caches这个函数进行批量的ids的pote_term和post_meta的请求:

1
_prime_post_caches( $ids, $q['update_post_term_cache'], $q['update_post_meta_cache'] );

它的源代码很好的解释了它的工作原理是:

1
2
3
4
5
6
7
8
9
10
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)", join( ",", $non_cached_ids ) ) );
 
		update_post_caches( $fresh_posts, 'any', $update_term_cache, $update_meta_cache );
	}
}

首先使用_get_non_cached_ids函数获取未缓存的post_ids(如果开启了Memcached,这里就可以自动实现返回为空,就会大大减少SQL请求),然后使用一条IN查询获取这些post_ids的内容,最后再使用update_post_caches将新获取的posts缓存起来,然后并且一次性求获取所有相关的post_term和post_meta。

lazy_load_term_meta 参数

是否延迟加载term meta的内容,如果没有设置,默认根据update_post_term_cache的值而定。

如果为true的话,WP_Query会把列表页所有的term_ids临时存储下来,在当前页第一次使用get_term_meta函数的时候,把term_ids的所有term_meta一次全部请求出来。

如果设置为false的话,每个get_term_meta的函数,都会产生一条SQL请求。

当然你也可以自己收集所有相关的term_ids,然后使用update_termmeta_cache($term_ids)来一次获取所有term_meta的值。

原文地址:http://blog.wpjam.com/m/wp_query-cache-args/

精品推荐: