定時將草稿箱中的文章改為已經發布的狀態,純代碼實現的方法。您也可以通過這種方法實現其他定時任務。
當我們使用采集插件采集到文章以后,并不想讓它立刻發布,而是希望它在規定的時間點發布。這樣做經驗上來看是有利于SEO的。但是每天都去手動去更新一下文章狀態顯得太low了。下面的代碼可以幫你實現定時發布的功能:
//定時任務,每天凌晨0點鐘
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 );
}
}
}
請將上面的代碼復制到主題的 functions.php 文件,或者子主題的 functions.php 文件中。
如果時間不準確,請將下面代碼也放入 functions.php 文件,刷一下首頁,然后刪掉即可。
$times = wp_next_scheduled( 'zrz_post_schedule_event' );
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');
發散一下,你可以通過這種方式進行其他定時任務,比如定時評論、定時通知、定時更新數據等等。以上代碼沒有實際測試過,有問題請在下面留言!