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:
<?php //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:
For more info on the wp_insert_post() function visit check the codex page at: http://codex.wordpress.org/Function_Reference/wp_insert_post
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: