wp_get_schedules()
概述
wp_get_schedules() 函数用于检索 WordPress 中支持的事件重复计划。默认包括 'hourly'、'twicedaily'、'daily' 和 'weekly',开发者可通过 'cron_schedules' 过滤器添加自定义计划。
关键要点
- 函数返回一个数组,键为计划名称(如 'hourly'),值为包含 'interval'(秒数)和 'display'(描述)的数组。
- 默认计划基于常量如 HOUR_IN_SECONDS、DAY_IN_SECONDS 等定义。
- 插件可通过 'cron_schedules' 过滤器添加新计划,例如添加 'monthly' 计划。
- 函数内部使用 array_merge() 合并默认计划和过滤后的自定义计划。
代码示例
add_filter( 'cron_schedules', 'cron_add_weekly' );
function cron_add_weekly( $schedules ) {
$schedules['weekly'] = array(
'interval' => 604800,
'display' => __( 'Once Weekly' )
);
return $schedules;
}注意事项
- 'interval' 应以秒为单位定义,建议使用 WordPress 常量(如 MONTH_IN_SECONDS)以提高可读性。
- 'display' 应使用 __() 函数进行本地化翻译。
- 从 WordPress 5.4.0 开始,默认添加了 'weekly' 计划。
Retrieves supported event recurrence schedules.
Description
The default supported recurrences are ‘hourly’, ‘twicedaily’, ‘daily’, and ‘weekly’.
A plugin may add more by hooking into the ‘cron_schedules’ filter.
The filter accepts an array of arrays. The outer array has a key that is the name of the schedule, for example ‘monthly’. The value is an array with two keys, one is ‘interval’ and the other is ‘display’.
The ‘interval’ is a number in seconds of when the cron job should run.
So for ‘hourly’ the time is HOUR_IN_SECONDS (60 * 60 or 3600). For ‘monthly’, the value would be MONTH_IN_SECONDS (30 * 24 * 60 * 60 or 2592000).
The ‘display’ is the description. For the ‘monthly’ key, the ‘display’ would be __( 'Once Monthly' ).
For your plugin, you will be passed an array. You can add your schedule by doing the following:
// Filter parameter variable name is 'array'.
$array['monthly'] = array(
'interval' => MONTH_IN_SECONDS,
'display' => __( 'Once Monthly' )
);
Skip to note 2 content
Codex
Basic Example
The ‘display’ is the description. For the ‘weekly’ key, the ‘display’ would be
__( 'Once Weekly' );For your plugin, you will be passed an array. You can easily add a new interval schedule by doing the following using the ‘cron_schedules’ filter.
add_filter( 'cron_schedules', 'cron_add_weekly' ); function cron_add_weekly( $schedules ) { // Adds once weekly to the existing schedules. $schedules['weekly'] = array( 'interval' => 604800, 'display' => __( 'Once Weekly' ) ); return $schedules; }