check_and_publish_future_post()
云策文档标注
概述
check_and_publish_future_post() 函数用于发布预定未来的文章,并确保文章状态为 'future'。它作为 cron 事件 'publish_future_post' 的调用函数,提供安全机制防止误发布草稿等非未来状态文章。
关键要点
- 函数通过 get_post() 获取文章对象,并检查 post_status 是否为 'future',否则直接返回。
- 如果文章的预定发布时间晚于当前时间,会清除已安排的 'publish_future_post' 事件并重新调度,以避免提前发布。
- 当时间条件满足时,调用 wp_publish_post() 发布文章,该函数无返回值。
- 此函数自 WordPress 2.5.0 版本引入,主要用于 cron 系统自动化发布流程。
代码示例
function check_and_publish_future_post( $post ) {
$post = get_post( $post );
if ( ! $post ) {
return;
}
if ( 'future' !== $post->post_status ) {
return;
}
$time = strtotime( $post->post_date_gmt . ' GMT' );
// Uh oh, someone jumped the gun!
if ( $time > time() ) {
wp_clear_scheduled_hook( 'publish_future_post', array( $post->ID ) ); // Clear anything else in the system.
wp_schedule_single_event( $time, 'publish_future_post', array( $post->ID ) );
return;
}
// wp_publish_post() returns no meaningful value.
wp_publish_post( $post->ID );
}注意事项
函数依赖于 cron 事件触发,需确保 'publish_future_post' 事件正确配置。参数 $post 可以是文章 ID 或 WP_Post 对象,无效输入将导致函数提前返回。在重新调度事件时,使用 GMT 时间进行计算以确保准确性。
原文内容
Publishes future post and make sure post ID has future post status.
Description
Invoked by cron ‘publish_future_post’ event. This safeguard prevents cron from publishing drafts, etc.
Parameters
$postint|WP_Postrequired-
Post ID or post object.
Source
function check_and_publish_future_post( $post ) {
$post = get_post( $post );
if ( ! $post ) {
return;
}
if ( 'future' !== $post->post_status ) {
return;
}
$time = strtotime( $post->post_date_gmt . ' GMT' );
// Uh oh, someone jumped the gun!
if ( $time > time() ) {
wp_clear_scheduled_hook( 'publish_future_post', array( $post->ID ) ); // Clear anything else in the system.
wp_schedule_single_event( $time, 'publish_future_post', array( $post->ID ) );
return;
}
// wp_publish_post() returns no meaningful value.
wp_publish_post( $post->ID );
}
Changelog
| Version | Description |
|---|---|
| 2.5.0 | Introduced. |