快速简便的方法
问题可能是您尝试从错误的路径中包含 wp-load.php。在 CLI 环境中,路径与对文件执行 HTTP 请求时的路径不同。所以有了这个你应该解决你的问题:
require(dirname(__FILE__) . '/../../../wp-config.php');
正确但更长的方法
基于他链接的cale_b cmets 和this article,通过Wordpress Cron job 有一个更合适的方法。
首先在您的插件中添加一个包含需要执行的代码的函数,我们称之为my_cron_job()。您最终可以只在此函数中包含您已经编写的脚本。然后添加以下内容以安排每 5 分钟执行一次:
// Define a new interval (5 minutes)
add_filter('cron_schedules', 'fively_interval');
function fively_interval($interval) {
$interval['fively'] = array('interval' => 5*60, 'display' => 'Once 5 minutes');
return $interval;
}
// Register the hook on plugin activation
register_activation_hook(__FILE__, 'my_cron_job_activation');
add_action('my_cron_event', 'my_cron_job');
function my_cron_job_activation() {
wp_schedule_event(time(), 'fively', 'my_cron_event');
}
// Unregister the hook on plugin deactivation
register_deactivation_hook( __FILE__, 'my_cron_job_deactivation' );
function my_cron_job_deactivation(){
wp_clear_scheduled_hook( 'my_cron_event' );
}
然后将你的 cron 设置为每 5 分钟执行一次 wp-cron.php:
*/5 * * * * php-cli -f [path to your WP]/wp-cron.php
更新
首先使用服务器cron选择执行 wp-cron.php em>的选项时,您应该禁用默认的WP CRON行为(通过Web访问的Cron执行):
define('DISABLE_WP_CRON', true);
其次,至于您关于 WP Cron 可靠性的问题,我确实看到了一个潜在的缺陷。我不是 100% 确定这一点,但我认为 wp_schedule_event 可能与服务器 cron 不同步,因为只有在间隔过去时才会执行作业。因为它将根据与服务器 cron 时间略有不同的脚本的执行时间重新安排。
例如:
00:00:00:000 Server cron execute wp-cron.php
00:00:00:100 The job can be executed, so let it run
00:00:00:200 Wordpress finished to execute the job - it schedule the event in 5min
00:05:00:000 Server cron execute wp-cron.php
00:05:00:100 The job is planned for 00:05:00:200, no execution !
00:10:00:000 Server cron execute wp-cron.php
00:10:00:100 The job is executed
这当然是理论,也许这并不准确。我建议做一些测试,看看它的表现如何。如果它确实表现得像我认为的那样,我建议将wp_schedule_event 更改为较低的间隔 - 例如4分钟。
add_filter('cron_schedules', 'fourly_interval');
function fourly_interval($interval) {
$interval['fourly'] = array('interval' => 4*60, 'display' => 'Once 4 minutes');
return $interval;
}
所以我们将有以下内容:
00:00:00:000 Server cron execute wp-cron.php
00:00:00:100 The job can be executed, so let it run
00:00:00:200 Wordpress finished to execute the job - it schedule the event in 4min
00:05:00:000 Server cron execute wp-cron.php
00:05:00:100 The job is planned for 00:04:00:200, so let it run!
00:10:00:000 Server cron execute wp-cron.php
00:00:00:200 Wordpress finished to execute the job - it schedule the event in 4min
00:10:00:100 The job is executed (planned for 00:09:00:200)
禁用默认的 WP Cron 行为后,它应该可以完美运行。