纯代码实现 WP 草稿文章每天定时发布
[ttr2v]
add_action( 'wp', 'zrz_post_schedule' );
function zrz_post_schedule() {
if (!wp_next_scheduled( 'zrz_post_schedule_event' )) {
$date = new DateTime( 'tomorrow', new DateTimeZone('Asia/Shanghai') );
$timestamp = $date->getTimestamp();
wp_schedule_event($timestamp, 'daily', 'zrz_post_schedule_event');
}
}
//修改文章状态动作
add_action( 'zrz_post_schedule_event', 'zrz_post_schedule_do_this_daily' );
function zrz_post_schedule_do_this_daily() {
$args = array(
'orderby' => 'date',//按照时间排序
'order' => 'ASC',//升序排列,ID从小到大
'post_type' => 'post',//文章类型
'post_status' => 'draft',//只检查文章状态是草稿的文章
'posts_per_page' => 10,//要发布的数量
);
$posts = get_posts( $args );
if(count($posts) > 0){
foreach ($posts as $post) {
$my_post = array(
'ID' => $post->ID,
'post_status' => 'publish',
);
wp_update_post( $my_post );
}
}
}
[/ttr2v]
请将上面的代码复制到主题的 functions.php 文件,或者子主题的 functions.php 文件中。
如果时间不准确,请将下面代码也放入 functions.php 文件,刷一下首页,然后删掉即可。
wp_unschedule_event( $times, 'zrz_post_schedule_event' );
$date = new DateTime( 'tomorrow', new DateTimeZone('Asia/Shanghai') );
$timestamp = $date->getTimestamp();
wp_schedule_event($timestamp, 'daily', 'zrz_post_schedule_event');