How to insert post with cron job in Wordpress

2019-09-07 04:18发布

I want to make a plugin that that creates a new posts every 30 minutes using cron job. I have already create a new interval for my cron job. I think tha problem is in inserting a new post. I am not sure can you help me?

<?php
/*
Plugin Name:
Description:
Version: 1.0
Author:
*/

add_filter('cron_schedules', 'new_interval');

// add once 30 minute interval to wp schedules
function new_interval($interval) {
    $interval['minutes_30'] = array('interval' => 30*60, 'display' => 'Once 30 minutes');

    return $interval;
}

function InitiateMyCron() {
    if (!wp_next_scheduled('MyCronEvent')) {
        wp_schedule_event(time(), 'minutes_30', 'MyCronAction');
    }
}

function MyCronAction() {
    //do my cron every 30 minutes
    $new_post = array(
    'post_title' => 'Cron job New Post',
    'post_content' => 'Lorem ipsum dolor sit amet...',
    'post_status' => 'publish',
    'post_date' => date('Y-m-d H:i:s'),
    'post_author' => 1,
    'post_type' => 'post',
    'post_category' => array(6, 2)
    );

    $post_id = wp_insert_post($new_post);
}

?>

what am I doing wrong?

Thank you in advance.

1条回答
别忘想泡老子
2楼-- · 2019-09-07 05:09

Don't forget WordPress cron "mechanism" is still "non-automatic" emulator. If visitors (peoples, search engines, etc) are visiting your website every minutes - cron will work. If visitors don't "touch" your website - cron will not work.

查看更多
登录 后发表回答