Get post ID from wp_insert_post()

You’ll have to do this in two steps. First, you will create a post in the draft mode, using wp_insert_post(). The wp_insert_post itself will return to you the ID of the inserted post:

<?php
$new_post = array(
    'post_title' => 'Draft title',
    'post_status'   => 'draft'
    'post_type'     =>      'my_custom_type'
);
$postId = wp_insert_post($new_post);
?>

<form method="post" action="your-action.php">
    <p>Hey! You are creating the post #<?php echo $postId; ?></p>
    <input type="hidden" name="draft_id" value="<?php echo $postId; ?>">
    ...
</form>

After that, in the action page, you will get the draft id and update the post. You’ll use wp_update_post informing the draft ID.

<?php
$draftId = $_POST['draft_id'];
...

$updated_post = array(
    'ID'            =>      $draftId,
    'post_title'    =>      $title,
    ...
    'post_status'   =>      'publish', // Now it's public
    'post_type'     =>      'my_custom_type'
);
wp_update_post($updated_post);
?>

Hope it helps 🙂

Leave a Comment