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!
以下例項透過函式 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 資料快取