可在不同主機的wordpress設置此功能互相關心,function如下
// 添加檢測網站狀態的函數 function check_websites_status() { $urls = [ 'https://www.yoursite1.com', 'https://www.yoursite2.com' ]; $error_urls = []; foreach ($urls as $url) { $response = wp_remote_get($url); if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) { $error_urls[] = $url; } } if (!empty($error_urls)) { $to = 'yourmailid@gmail.com'; $subject = '網站狀態錯誤'; $message = '以下網站發生錯誤:' . "\r\n" . implode("\r\n", $error_urls); wp_mail($to, $subject, $message); } } // 設定計劃任務 function schedule_websites_check() { if (!wp_next_scheduled('check_websites_status_hook')) { wp_schedule_event(time(), 'hourly', 'check_websites_status_hook'); } } add_action('wp', 'schedule_websites_check'); // 註冊計劃任務的動作 add_action('check_websites_status_hook', 'check_websites_status'); // 確保計劃任務在插件或主題停用時移除 function unschedule_websites_check() { $timestamp = wp_next_scheduled('check_websites_status_hook'); if ($timestamp) { wp_unschedule_event($timestamp, 'check_websites_status_hook'); } } register_deactivation_hook(__FILE__, 'unschedule_websites_check');
寫入後再排定cron運作即可,這個範例為每小時偵測1次,有問題才會回報,你初次設定時可以故意輸入一個會報錯的網址,看能不能順利收到email
PS.網站必須要有email寄送功能唷,不然做這個設定也是白搭