2

I'm trying to schedule a post that is currently a draft:

function schedule() {

$postdate = date('2014-06-11 00:30:00');
$post = array(
    'ID' => 11,
  'post_status'    => 'future',
  'post_type'      => 'post',
  'post_author'    => '1',
  'ping_status'    => 'closed',
  'to_ping'        => 'http://rpc.pingomatic.com/',
  'post_date_gmt'  => $postdate
);  
wp_insert_post( $post ); 
}
add_action('wp_head', 'schedule');

Nothing happens to the post in question though, it still remains a draft? Is there some other way to schedule a post, or is something wrong with my code?

2

You shouldn't be using wp_insert_post() to manipulate existing post. That's what wp_update_post() is for.

You can pass true as second argument to either so that return in case of failure contains WP_Error object rather than unhelpful 0. Helps with debug a lot.

  • wp_update_post() has a weird behavior - when I schedule a post i.e. 'post_status' => 'future', it publishes it immediately on the first run of the function, and only then on the second run it sets the appropriate date and time for publishing? – kat Jun 10 '14 at 18:17
2

As Rarst mentioned I had to use wp_update_post(), but then there is a little trick - one must also set edit_date = true otherwise it has funny behavior. The final code looks like this:

function schedule() {

$postdate = date('2014-06-11 01:00:00');
$postdate_gmt = date('2014-06-11 05:00:00');
$post = array(
    'ID' => 11,
  'post_status'    => 'future',
  'post_type'      => 'post',
  'post_author'    => '1',
  'ping_status'    => 'closed',
  'to_ping'        => 'http://rpc.pingomatic.com/',
  'post_date_gmt'  => $postdate_gmt,
  'post_date'  => $postdate,
  'edit_date' => 'true'
);  

wp_update_post( $post, true ); 
}

add_action('wp_head', 'schedule');

And here's how it can work for many posts, using a text file:

Text File:

postid,server_time,gmt_time
postid,server_time,gmt_time
postid,server_time,gmt_time
postid,server_time,gmt_time
...

Function:

function schedule() {

    $fh = @fopen( dirname( __FILE__ ) . '/schedule.txt', 'r' );

    if ( $fh ) {
        while ( ( $line = fgets( $fh ) ) !== false ) {
            $ids = explode( ',', $line );
            array_walk( $ids, 'trim' );

$postdate = date($ids[1]);
$postdate_gmt = date($ids[2]);
$post = array(
    'ID' => $ids[0],
  'post_status'    => 'future',
  'post_type'      => 'post',
  'post_author'    => '5',
  'ping_status'    => 'closed',
  'to_ping'        => 'http://rpc.pingomatic.com/',
  'post_date_gmt'  => $postdate_gmt,
  'post_date'  => $postdate,
  'edit_date' => 'true'
);  

wp_update_post( $post, true ); 
        }
    }

    }

add_action('wp_head', 'schedule');

Many thanks to everyone who helped in this and other threads!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.