纯代码实现 WP 采集到的草稿文章每天定时发布

定时将草稿箱中的文章改为已经发布的状态,纯代码实现的方法。您也可以通过这种方法实现其他定时任务。

当我们使用采集插件采集到文章以后,并不想让它立刻发布,而是希望它在规定的时间点发布。这样做经验上来看是有利于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');


发散一下,你可以通过这种方式进行其他定时任务,比如定时评论、定时通知、定时更新数据等等。以上代码没有实际测试过,有问题请在下面留言!

随记

柒比贰使用记录

2018-10-28 0:59:28

随记

2017,网页设计期末作业

2018-11-29 14:41:32

⚠️
Npcink上的部份代码及教程来源于互联网,仅供网友学习交流,若您喜欢本文可附上原文链接随意转载。
无意侵害您的权益,请发送邮件至 1355471563#qq.com 或点击右侧 私信:Muze 反馈,我们将尽快处理。
0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索