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?

wp_insert_post()

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:

<?php

//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: 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:

http://codex.wordpress.org/Function_Reference/wpdb_Class#Class_Variables

Be Sociable, Share!

    7 Comments

    1. and without inserting post.
      $newest_post_id = $posts[0]->ID

      Reply
      • Hi Saroj,

        Good point. That is a very easy way to get that last ID during the loop.

        Thanks for your contribution! I’ll keep your approach in mind now during development 😉

        Reply
    2. Very useful post , thanks alot 🙂

      Reply
    3. Thanks, very useful! This will save me a lot of time 😀

      Reply

    Trackbacks/Pingbacks

    1. […] How to get the ID of the last insert post in WordPress | Vidal Quevedo […]

    Leave a Comment