How to get last inserted row ID from WordPress database?
Solution 1:
Straight after the $wpdb->insert()
that does the insert, do this:
$lastid = $wpdb->insert_id;
More information about how to do things the WordPress way can be found in the WordPress codex. The details above were found here on the wpdb class page
Solution 2:
This is how I did it, in my code
...
global $wpdb;
$query = "INSERT INTO... VALUES(...)" ;
$wpdb->query(
$wpdb->prepare($query)
);
return $wpdb->insert_id;
...
More Class Variables
Solution 3:
I needed to get the last id way after inserting it, so
$lastid = $wpdb->insert_id;
Was not an option.
Did the follow:
global $wpdb;
$id = $wpdb->get_var( 'SELECT id FROM ' . $wpdb->prefix . 'table' . ' ORDER BY id DESC LIMIT 1');