2017-05-26 51 views
0

我一直在使用WP_CACHE功能在我的網站提高主頁的性能和避免多次查詢。wp_cache_get不wp_head掛鉤工作

我已經把代碼放到我的function.php像下面,

add_action('wp_head', 'set_data_in_cache'); 

function set_data_in_cache(){ 
    if (is_front_page()) { 
     gloabl $wpdb; 
     $dataInCache = wp_cache_get('post_data');   
     if($dataInCache === false){ 
      $result = $wpdb->query('some query'); 
      wp_cache_set('post_data',$result,'',86400);   
     } 
     else{ 
      //data in cache 
     } 
    } 
} 

我一直在檢查,在頁面加載每次$ dataInCache變量是空的。意味着沒有數據被存儲在緩存中。 頁面加載並將數據設置爲緩存後,它不應該爲空。

但是$ dataInCache = wp_cache_get( 'post_data');在身體標籤內完美工作,數據正在完美顯示。

那是什麼錯在我的代碼?

+0

你有沒有用「初始化」行動試過嗎? –

+0

其實你是不是在這是在「初始化」鉤wp_head –

+0

文件開始獲得這個職位數據我無法設置頭版因此需要使用wp_head掛鉤 –

回答

0

您需要使用武力在裏面wp_cache_get真正得到結果。

wp_cache_get($key, '', true); 

它也將是很好的定義了一個組,然後得到緩存,因此,這將是在頭可用。

+0

nope,不能在兩種方式工作:( –