當(dāng)我們使用采集插件采集到文章以后,并不想讓它立刻發(fā)布,而是希望它在規(guī)定的時(shí)間點(diǎn)發(fā)布。這樣做經(jīng)驗(yàn)上來看是有利于SEO的。但是每天都去手動(dòng)去更新一下文章狀態(tài)顯得太low了。下面的代碼可以幫你實(shí)現(xiàn)定時(shí)發(fā)布的功能:
//定時(shí)任務(wù),每天凌晨0點(diǎn)鐘
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)動(dòng)作
add_action( 'zrz_post_schedule_event', 'zrz_post_schedule_do_this_daily' );
function zrz_post_schedule_do_this_daily() {
$args = array(
'orderby' => 'date',//按照時(shí)間排序
?'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 );
}
}
}
請將上面的代碼復(fù)制到主題的 functions.php 文件,或者子主題的 functions.php 文件中。
如果時(shí)間不準(zhǔn)確,請將下面代碼也放入 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ā)散一下,你可以通過這種方式進(jìn)行其他定時(shí)任務(wù),比如定時(shí)評(píng)論、定時(shí)通知、定時(shí)更新數(shù)據(jù)等等。以上代碼沒有實(shí)際測試過,有問題請?jiān)谙旅媪粞裕?/strong>