Lesson 4 of 9 · 28m
Database Access: Options, Post Meta, WP_Query, and Custom Tables
How to choose the right storage primitive, use $wpdb safely, design custom tables with dbDelta, and avoid query patterns that collapse at scale.
The most consequential plugin decision is where data lives. WordPress gives you posts, post meta, users, user meta, options, terms, comments, and custom tables. None is universally correct. Choose wrong and you will spend years compensating with caching and denormalization.
A useful rule: if the data is content meant to be queried, rendered, revised, and permissioned like content, use posts. If it is configuration, use options. If it is high-volume structured operational data with relational queries, use a custom table. If you need audit trails, idempotent imports, queues, or millions of rows, do not pretend post meta is a database design.
$wpdb is a thin layer, not an ORM
global $wpdb;
$rows = $wpdb->get_results(
$wpdb->prepare(
"SELECT sku, quantity FROM {$wpdb->prefix}acme_inventory WHERE warehouse_id = %d AND quantity < %d",
$warehouse_id,
$threshold
),
ARRAY_A
);Never concatenate request values into SQL, even after sanitize_text_field(). Sanitization is not SQL encoding. Use %d, %f, %s; use $wpdb->prepare() for every variable expression. For identifiers such as table names, do not accept them from users at all — select from a fixed allowlist.
Check false from $wpdb->query() and $wpdb->last_error during development, but do not expose database errors to users. They disclose schema details and sometimes query fragments.
Custom tables deserve boring design
function acme_create_inventory_table(): void {
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE {$wpdb->prefix}acme_inventory (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
warehouse_id bigint(20) unsigned NOT NULL,
sku varchar(80) NOT NULL,
quantity int(11) NOT NULL DEFAULT 0,
updated_at datetime NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY warehouse_sku (warehouse_id, sku),
KEY quantity_idx (quantity)
) $charset_collate;";
dbDelta($sql);
}dbDelta() is fussy: spacing matters, key definitions matter, and it is not a general migration engine. Keep the canonical schema in one function. Test upgrades on a copy with realistic row counts; adding an index to a million-row table can take minutes and must not be triggered synchronously by an admin page load.
Query behavior is the real bottleneck
The expensive mistakes are familiar:
posts_per_page => -1on an unbounded post type.- Meta queries with several
ORclauses on large sites. ORDER BY RAND().- Counting rows repeatedly instead of caching or storing aggregates.
- Querying custom tables without indexes matching the
WHEREandORDER BYcolumns.
Use EXPLAIN on MySQL/MariaDB for critical queries. WordPress hosting often gives you little control over buffer sizes, so index design and result cardinality are your levers. Persistent object caches help, but they do not fix a fundamentally bad query.
Transactions and concurrency
$wpdb can execute transactions on InnoDB tables, but WordPress does not manage them for you. For counters and inventory-like updates, prefer atomic operations:
UPDATE wp_acme_inventory
SET quantity = quantity - 1
WHERE warehouse_id = 12 AND sku = 'SKU-481' AND quantity > 0Then inspect affected rows. A zero-row update means the stock was already gone; it is not an exception. For multi-step changes, wrap in START TRANSACTION / COMMIT, catch failures, and always ROLLBACK in failure paths.
Field notes
$wpdb->insert()and$wpdb->update()accept data formats; pass them explicitly.- Use
bigint(20) unsignedfor IDs that may reference core object IDs. - Do not store serialized arrays in custom tables unless you never need to query inside them.
- Large imports need batching,
DELETE/INSERTcheckpoints, and progress state — not one 30-second request.
Was this lesson helpful?