How to get the ID of the last insert post in WordPress

When programming for WordPress, sometimes you may need to get the ID of the last post that was inserted to the database (à la MySQL’s ‘LAST_INSERT_ID’).  Here’s the thing: the wp_insert_post() function returns the newly inserted post’s ID, so you can use it to perform more stuff on the post right away, without having to mess around with any SQL commands to retrieve it. Clever, huh?


The function wp_insert_post() does that, it inserts posts into the WP database. You only need to create a required object (or array) containing  a few  properties of the new post (such as post_title, post_content, post_status, etc) to get it rolling, and it will fill in any blanks you might’ve missed.

But the main point here is that the wp_insert_post() function returns the newly inserted post’s ID.

Here’s an example:


//insert new post
 // Create post object
 $my_post = array();
 $my_post['post_title'] = 'Hello world';
 $my_post['post_content'] = 'This is a sample post';
 $my_post['post_status'] = 'published';
 $my_post['post_author'] = 7; //the id of the author
 $my_post['post_category'] = array(10,12); //the id's of the categories

 // Insert the post into the database
 $post_id = wp_insert_post( $my_post ); //store new post id into $post_id


Now the $post_id variable contains the id of the last inserted post, and you can use it in the rest of your script.  For example, we could use it now to assign tags to the recently added post:


//now add tags to new post using the last inserted post id in the $post_id var
 $tags = array('html', 'css', 'javascript');
 wp_set_object_terms( $post_id, $tags, 'post_tag', true );    


Cool, huh?

For more info on the wp_insert_post() function visit check the codex page at:

Getting last insert id from the $wpdb object:

The $wpdb object stores the last insert post id as a property. I tried using it and it didn’t work for me, but you can still try to use it. Here’s the codex page: