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 數據緩存