Tips and Tricks

WordPress Last Insert ID | Get wpdb Last Insert ID in while loop

WordPress Last Insert ID : In WordPress, at some point or the other, you may have come across a situation where you would need to get the last insert id i.e. the value of the auto-increment column as a result of insert operation performed. If you are running a normal SQL query, you would get the last insert ID using mysql_insert_id(). But do you know how to get the last inserted row ID in WordPress? It’s very simple & the code is just 1 line. Read on to find out the solution.

In WordPress, get Last Insert ID using wpdb  in while loop

Let’s assume that you are working with WordPress and that you are inserting multiple products into the database using a custom for/foreach loop. In order to find out the last inserted row ID, you would generally use mysql_insert_id(). So now, we would need the equivalent of the mysql_insert_id() in WordPress using wpdb. We can get the last inserted id in WordPress using the following code:

So just place the above line of code, just below the actual wpdb query. Following is an example:

So that’s how you can get the last inserted row ID value in WordPress.

Simple, isn’t it?

Do you know of any other ways to get the last inserted ID in WordPress? Feel free to share by commenting below.

Share your thoughts, comment below now!