2016-08-03 22 views
1

這是一個更多的代碼審查請求,而不是一個錯誤。問題是這是否是編寫以下函數的「正確方法」。如何檢測WordPress中帖子數量的變化?

我想運行一個php cron任務,檢查博客中的帖子數量是否發生了變化,如果是的話 - 刪除主頁緩存的html。

我可以使用WP Crontrol插件來設置一個php cron任務。我需要的是創建一個全局變量的函數,它將存儲在帖子數量的某個位置(我使用wp_options表格),並且每次向服務器詢問當前的帖子數量是多少。而且如果有差異,清除緩存。以下是我最終寫作的功能。是否有意義,或者是有什麼我應該做不同(/更好?)

if_new_posts_delete_homepage_cache = function() { 
    // get current number of posts 
    // https://codex.wordpress.org/Function_Reference/wp_count_posts 
    $count_posts = wp_count_posts(); 
    $new_number_of_posts = $count_posts->publish; 

    // https://developer.wordpress.org/reference/functions/get_option/ 
    // set number of posts for the first time 
    // some code that adds the current 
    $old_number_of_posts = get_option("number of published posts", 0); 

    // if the option is not set - update it 
    // https://codex.wordpress.org/Function_Reference/add_option 
    if($old_number_of_posts == 0) { 
     add_option("number of published posts", $new_number_of_posts); 
     $old_number_of_posts = $new_number_of_posts; 
    } 

    if($old_number_of_posts < $new_number_of_posts) { 
    unlink(dirname(__FILE__) . "/wp-content/cache/supercache/sitename.com/" . 'index.html.gz'); 
    } 
} 

if_new_posts_delete_homepage_cache(); 

回答

1

評論

你的代碼是一個不錯的黑客清除緩存,但它畢竟是一個黑客,我不會在生產環境中使用它。

原因是 -

  1. 正如其他人所指出的,你的代碼不覆蓋邊緣情況。如果您發佈帖子並取消發佈其他帖子,則數量保持不變。 cron不會運行。在一個多作者的網站上,這個邊緣案例可能會頻繁發生,你的cron會成爲一個命中和錯過。
  2. 這不會利用WordPress爲您提供的功能來處理諸如post_publish之類的事件。
  3. 雖然每次您的cron運行時添加的數據庫的效果可能不會太大,但我寧願避免它。

解決方案

現在回答你的問題,我會用行動掛鉤。 https://developer.wordpress.org/reference/functions/add_action/

function clearCacheOnStateChange($new_status, $old_status, $post) { 
    if ($new_status != $old_status) { 
     unlink(dirname(__FILE__) . "/wp-content/cache/supercache/sitename.com/" . 'index.html.gz');  
    } 
} 
add_action( 'transition_post_status', 'clearCacheOnStateChange', 10, 3); 
+0

謝謝@Shivam,非常有趣。如果我可能會問,你是如何知道「transition_post_status」的? –

+1

我記得以前用過這個。 API參考 - https://developer.wordpress.org/reference/hooks/transition_post_status/ –

+0

超級酷。謝謝。 –

2

首先回答你的問題,我想提取字符串「發佈的文章數量」爲一個常數,像OPTION_KEY。 我還想使它更簡潔,使用數據庫y和前綴來防止衝突。像'npdhc:number_posts'。


要回答你沒有問這樣的問題:我不認爲職位數是做一個關於破壞緩存決定的最佳途徑。 理論上,您可以進入邊緣條件,在該條件下發布一篇文章並刪除另一篇文章,緩存不會更新。

它更正確,也更簡單的代碼,只需要使用的最後一個職位的修改時間(我認爲這是$post_modified_gmt但不知道)