0

I'm building a script which creates new blog posts from an external source. my code is as follows:

    // Load WordPress
    require_once '../../wp-load.php';
    require_once ABSPATH . '/wp-admin/includes/taxonomy.php';
    // Set the timezone so times are calculated correctly
    date_default_timezone_set('Europe/London');
    // Create post
    $id = wp_insert_post(array(
        'post_title'    => $headline,
        'post_content'  => $body,
        'post_date'     => date('Y-m-d H:i:s'),
        'post_author'   => $user_id,
        'post_type'     => 'post',
        'post_status'   => 'draft',
    ));

if($id){
    // Set category - create if it doesn't exist yet
    wp_set_post_terms($id, wp_create_category($region), 'category');
    // Add meta data, if required
    add_post_meta($id, 'meta_key', $metadata);
    echo $open_wrap."<h2>Success!</h2>
    <p>The post has been added to the Bulletins Category as a <strong>draft</strong>.<br>
    Please $wp_url to Publish or Schedule the post.</p> 
    ".$close_wrap;

} else {
    echo "WARNING: Failed to insert post into WordPress\n";
}

I'd like to allow the user to set the publication date, so they can create the post and it will publish automatically on that date.

Is there a wordpress function for adding a publication date?

0

I don't know why you are loading WordPress by including the core files, there should be something wrong at that point.

Anyway, to schedule an event, you can use wp_schedule_single_event. This function accepts 3 arguments:

wp_schedule_single_event( $timestamp, $hook, $args );

In your case, you can wrap wp_insert_post in a function, and then call it when the time arrives:

// Use this instead of wp_insert_post
wp_schedule_single_event( 'SET THE TIME HERE', 'schedule_my_post' );

// Add an action that runs the function
add_action( 'schedule_my_post','publish_my_post' );

// Now, do the actual publish
function publish_my_post($args){
    wp_insert_post($args);
}

Done.

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.