這是一個更多的代碼審查請求,而不是一個錯誤。問題是這是否是編寫以下函數的「正確方法」。如何檢測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();
謝謝@Shivam,非常有趣。如果我可能會問,你是如何知道「transition_post_status」的? –
我記得以前用過這個。 API參考 - https://developer.wordpress.org/reference/hooks/transition_post_status/ –
超級酷。謝謝。 –