How7o
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Reading: How to Retrieve the Last Inserted Row ID in WordPress
Share
How7oHow7o
Font ResizerAa
  • OS
Search
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Follow US
© 2024–2026 How7o. All rights reserved.
How7o > Free Laravel, PHP, WordPress & Server Tutorials > Web Development > How to Retrieve the Last Inserted Row ID in WordPress
Web Development

How to Retrieve the Last Inserted Row ID in WordPress

how7o
By how7o
Last updated: May 10, 2026
7 Min Read
WordPress $wpdb->insert_id — read after $wpdb->insert or $wpdb->query INSERT
SHARE

To wordpress wpdb insert id — grab the auto-increment value of the row you just created — read $wpdb->insert_id immediately after the insert call. It’s populated after every INSERT the current connection runs, whether via $wpdb->insert() or a raw $wpdb->query('INSERT ...'). This guide covers the common case, the $wpdb->insert() vs raw-query distinction, bulk-insert semantics, and the “check return first, then read the ID” safety rule.

Contents
  • TL;DR
  • The idiomatic call
  • Always check the return value first
  • Using $wpdb->query() directly
  • Bulk inserts
  • Frequently asked questions
  • Related guides
  • References

Last verified: 2026-04-23 on WordPress 6.5 and PHP 8.3. Originally published 2023-05-22, rewritten and updated 2026-04-23.

TL;DR

global $wpdb;

$ok = $wpdb->insert(
    $wpdb->prefix . 'my_table',
    array(
        'name'  => 'John',
        'email' => '[email protected]',
    )
);

if ( $ok === false ) {
    // handle insert failure — do NOT read insert_id
}

$last_id = $wpdb->insert_id;

The idiomatic call

$wpdb->insert(
    $wpdb->prefix . 'my_table',
    array(
        'name'  => 'John',
        'email' => '[email protected]',
    )
);

$last_id = $wpdb->insert_id;

$wpdb->insert() runs a parameterized INSERT against the named table and returns the number of rows inserted on success (1) or false on failure. After the call, the insert_id property holds MySQL’s LAST_INSERT_ID() for this connection — the auto-increment value of the new row.

No extra round trip, no second SELECT — MySQL returns the value as part of the INSERT result packet, and $wpdb exposes it on the property.

Always check the return value first

$ok = $wpdb->insert( $wpdb->prefix . 'my_table', array(
    'name'  => $name,
    'email' => $email,
) );

if ( $ok === false ) {
    return new WP_Error( 'db_insert_failed', $wpdb->last_error );
}

$last_id = $wpdb->insert_id;

If the insert fails — unique-constraint violation, dropped connection, NOT NULL column missing — $wpdb->insert_id still holds whatever value the previous successful insert left there. Reading it without checking the return value can make the code act on a stale ID. The $wpdb->last_error property is the MySQL error string you’d want to log.

wordpress wpdb insert_id — wpdb insert then read insert_id property, always check the return value first

Using $wpdb->query() directly

$sql = $wpdb->prepare(
    "INSERT INTO {$wpdb->prefix}my_table (name, email, created_at)
     VALUES (%s, %s, NOW())",
    $name,
    $email
);

$ok = $wpdb->query( $sql );

if ( $ok === false ) {
    return new WP_Error( 'db_insert_failed', $wpdb->last_error );
}

$last_id = $wpdb->insert_id;

The same insert_id property works when you’ve run the INSERT via $wpdb->query() (for expressions $wpdb->insert() can’t handle — NOW(), UUID(), subqueries). Reach for $wpdb->insert() when the values are simple; for SQL expressions in column values, fall back to query() + prepare().

Bulk inserts

$wpdb->query(
    "INSERT INTO {$wpdb->prefix}my_table (name, email) VALUES
        ('John', '[email protected]'),
        ('Jane', '[email protected]'),
        ('Mike', '[email protected]')"
);

$first_id = $wpdb->insert_id;                // e.g. 42
$rows     = $wpdb->rows_affected;            // 3
// Derived IDs: 42, 43, 44
$all_ids  = range( $first_id, $first_id + $rows - 1 );

MySQL returns the ID of the first row in a multi-row INSERT. The other IDs are contiguous — assuming no other inserts from a concurrent connection interleaved — and you can derive them from $wpdb->rows_affected. Don’t run N separate single-row inserts just to collect N IDs; that’s N round trips for no reason.

Caveat: if your table has innodb_autoinc_lock_mode = 2 (the default on MySQL 8.0+ in some deployments), the IDs may not be strictly contiguous across concurrent inserts. For absolute certainty, wrap the bulk insert in a transaction and re-SELECT the rows by a batch identifier.

Frequently asked questions

What’s the shortest wordpress wpdb insert id call?

Read $wpdb->insert_id right after $wpdb->insert(...) returns. The property holds the auto-increment value of the last INSERT the current connection performed — same semantics as MySQL’s LAST_INSERT_ID(). No extra query needed.

Is mysql_insert_id() the same thing?

It was, back in the mysql_* PHP extension days. That extension was removed in PHP 7, so mysql_insert_id() no longer exists. WordPress’s $wpdb->insert_id is the modern replacement — it wraps mysqli_insert_id() internally and gives you a WordPress-idiomatic API.

Can I use $wpdb->insert_id after $wpdb->query()?

Yes — it’s populated after any INSERT the connection runs, whether via $wpdb->insert(), $wpdb->query('INSERT ...'), or a prepared statement you execute manually. The rule: the property reflects the most recent INSERT, so read it immediately; a later non-INSERT query (SELECT, UPDATE) doesn’t overwrite it, but the next INSERT will.

What about bulk inserts — which ID do I get?

MySQL returns the ID of the first row in a multi-row INSERT. If you inserted 10 rows with auto-incrementing IDs starting at 42, $wpdb->insert_id is 42, and the other nine IDs are 43–51 (assuming no gaps). Don’t call ten separate single-row inserts to “get each ID” — that’s ten round trips for no reason. The first ID + row count is enough to derive the rest.

Does the property survive a database error?

No. If $wpdb->insert() fails (false return), $wpdb->insert_id holds whatever value the previous successful insert left there. Always check the return value before trusting the ID: if ($wpdb->insert(...) === false) { return new WP_Error(...); }. Otherwise you might end up acting on a stale ID.

Related guides

  • How to Prepare a %LIKE% SQL Statement in WordPress — the companion $wpdb->prepare pattern for reads.
  • How to Search Users by Multiple Fields in WordPress — built-in class for searches instead of raw $wpdb.
  • How to Order Posts by Meta Value in WordPress — another WP_Query vs raw SQL decision.
  • How to Retrieve the Last Inserted ID in Laravel — the Laravel-Eloquent equivalent of this pattern.

References

WordPress developer reference for $wpdb->insert and $wpdb->insert_id: developer.wordpress.org/reference/classes/wpdb/insert.

TAGGED:mysqlphpsqlwordpress

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
[mc4wp_form]
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Copy Link Print
Previous Article WordPress prepare LIKE SQL — %s placeholder + % wildcards in the value How to Prepare a %LIKE% SQL Statement in WordPress
Next Article WordPress disable revision and autosave — wp-config constants and wp_print_scripts dequeue How to Disable Revisions and Autosave in WordPress
Leave a Comment

Leave a Reply Cancel reply

You must be logged in to post a comment.

FacebookLike
XFollow
PinterestPin
InstagramFollow
Most Popular
Laravel Eloquent ORM — a model class mapping to a database table with query methods
Laravel Eloquent ORM: The Complete Guide to Querying Your Database
June 16, 2026
Set vi as the default editor in Ubuntu — a terminal opening the vim editor
How to Set vi (Vim) as the Default Editor in Ubuntu
June 8, 2026
rsync says ALL DONE but files are missing — a terminal showing ALL DONE next to an empty folder
rsync Says “ALL DONE” but Files Are Missing: How to Verify
June 8, 2026
Migrate a website to a new server with rsync — files copying from an old server to a new one over SSH
How to Migrate a Website to a New Server With rsync
June 8, 2026
Bun runtime — faster JS toolkit replacing npm in Laravel projects
How to Install Bun Runtime on Ubuntu (And Use It in a Laravel Project)
May 24, 2026

You Might Also Like

Use a JavaScript variable as an object key
Web Development

How to Use a Variable as an Object Key in JavaScript

5 Min Read
Laravel last inserted ID — Eloquent save populates model primary key illustration
Web Development

How to Retrieve the Last Inserted ID in Laravel Eloquent

8 Min Read
MySQL combine columns into string — CONCAT and CONCAT_WS
Web Development

How to Combine Multiple Columns into One String in MySQL

6 Min Read
JavaScript check HTTP referrer — document.referrer
Web Development

How to Check the HTTP Referrer with JavaScript

4 Min Read
How7o

We provide tips, tricks, and advice for improving websites and doing better search.

Tools

  • Age Calculator
  • Word Counter
  • Image Upscaler
  • Password Generator
  • QR Code Generator
  • See all tools→

Pranks

  • Fake Blue Screen Prank
  • Hacker Typer
  • Fake iMessage Generator
  • Windows XP Crash Prank
  • Windows 11 Update Prank
  • See all prank screens →

Company

  • About Us
  • Blog
  • Contact
  • Privacy Policy
  • Terms of Service
  • Sitemap
© 2024–2026 How7o. All rights reserved.
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?