定時將草稿箱中的文章改為已經(jīng)發(fā)布的狀態(tài),純代碼實現(xiàn)的方法。您也可以通過這種方法實現(xiàn)其他定時任務。
當我們使用采集插件采集到文章以后,并不想讓它立刻發(fā)布,而是希望它在規(guī)定的時間點發(fā)布。這樣做經(jīng)驗上來看是有利于SEO的。但是每天都去手動去更新一下文章狀態(tài)顯得太low了。下面的代碼可以幫你實現(xiàn)定時發(fā)布的功能:
//定時任務,每天凌晨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');
}
}
//修改文章狀態(tài)動作
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',//只檢查文章狀態(tài)是草稿的文章
?'posts_per_page' => 10,//要發(fā)布的數(shù)量
);
$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');
發(fā)散一下,你可以通過這種方式進行其他定時任務,比如定時評論、定時通知、定時更新數(shù)據(jù)等等。以上代碼沒有實際測試過,有問題請在下面留言!