_set_cron_array()
云策文档标注
概述
_set_cron_array() 函数用于更新 WordPress 的 cron 选项,将新的 cron 数组保存到数据库中。它处理 cron 数组的验证和版本设置,并支持在失败时返回 WP_Error。
关键要点
- 函数接受一个必需的数组参数 $cron,该数组应来自 _get_cron_array() 函数,用于更新 cron 选项。
- 可选参数 $wp_error 控制失败时是否返回 WP_Error 对象,默认值为 false。
- 函数内部会确保 $cron 为数组,并设置版本号为 2,然后使用 update_option() 保存到数据库。
- 返回值为 bool 或 WP_Error:成功时返回 true,失败时根据 $wp_error 返回 false 或 WP_Error。
- 该函数在 WordPress 5.7.0 版本中增加了 $wp_error 参数,5.1.0 版本修改了返回值以匹配 update_option() 的结果。
代码示例
function _set_cron_array( $cron, $wp_error = false ) {
if ( ! is_array( $cron ) ) {
$cron = array();
}
$cron['version'] = 2;
$result = update_option( 'cron', $cron, true );
if ( $wp_error && ! $result ) {
return new WP_Error(
'could_not_set',
__( 'The cron event list could not be saved.' )
);
}
return $result;
}注意事项
- 确保传入的 $cron 参数是有效的数组,否则函数会将其重置为空数组。
- 使用此函数时,需注意版本兼容性,特别是 $wp_error 参数在 WordPress 5.7.0 及以上版本才可用。
- 函数依赖于 update_option() 来保存数据,失败时可能返回 false 或 WP_Error,调用者应适当处理错误情况。
原文内容
Updates the cron option with the new cron array.
Parameters
$cronarray[]required-
Array of cron info arrays from _get_cron_array() .
$wp_errorbooloptional-
Whether to return a WP_Error on failure.
Default:
false
Source
function _set_cron_array( $cron, $wp_error = false ) {
if ( ! is_array( $cron ) ) {
$cron = array();
}
$cron['version'] = 2;
$result = update_option( 'cron', $cron, true );
if ( $wp_error && ! $result ) {
return new WP_Error(
'could_not_set',
__( 'The cron event list could not be saved.' )
);
}
return $result;
}
Changelog
| Version | Description |
|---|---|
| 5.7.0 | The $wp_error parameter was added. |
| 5.1.0 | Return value modified to outcome of update_option() . |
| 2.1.0 | Introduced. |