wordpress缓存函数介绍及使用

十度 wordpress 2015年12月20日 收藏

wordpress使用缓存来存储比较少变动的数据可以大大提供我们的wordpress性能,wordpress中常用的缓存函数如下:

函数中参数说明:

  • $key: 缓存的key值.
  • $data: 缓存的数据.
  • $group: (可选) 缓存数据组,在不同组之间你可以使用相同的key.
  • $expire: (可选)缓存的时间,单位为秒,默认为0(不过期).

函数介绍:

wp_cache_add( $key, $data, $group, $expire )

这个函数用于添加数据缓存,如果缓存 $key 存在则不添加缓存数据返回FALSE。

wp_cache_set( $key, $data, $group, $expire )

添加数据缓存。如果缓存项已经存在,那么它将被覆盖;如果没有的话,它将被创建。

wp_cache_get( $key, $group )
wp_cache_get( $key, $group = '', $force = false, $found = null )

读取缓存数据,如果该缓存数据不存在返回FALSE!

wp_cache_delete( $key, $group )

清除缓存数据

wp_cache_replace( $key, $data, $group, $expire )

该函数用于替换更新缓存数据,如果该缓存不存在则返回FALSE!

wp_cache_flush()

清空所有函数数据。

wp_cache_add_non_persistent_groups($groups)

Hints to the object cache that the group or list of groups should not be cached in persistent storage. This is useful when adding items to the cache that should only be available for the duration of a script session, and not beyond. $groups can be an array of strings, or a single group name. NB: only some caching plugins implement this function!

wordpress缓存应用实例

以下实例通过函数wp_cache_get获取key值为my_result的缓存数据,如果不存在则则通过函数wp_cache_set来设置缓存数据。

$result = wp_cache_get( 'my_result' );
if ( false === $result ) {
	$result = $wpdb->get_results( $query );
	wp_cache_set( 'my_result', $result );
} 
// 处理$result数据;

更多关于wordpress缓存的文章: wordpress数据缓存