WordPress

wpdb

wpdb is the PHP class WordPress uses to talk to its MySQL or MariaDB database, available in code as the global $wpdb. Core, themes, and plugins all send their queries through it.

How it is measured

Common methods are get_results(), get_row(), get_var(), get_col(), query(), insert(), update(), delete(), and prepare(). Properties include $wpdb->prefix, $wpdb->posts, $wpdb->last_query, $wpdb->last_error, and $wpdb->num_queries. insert() and update() escape values for you when you pass the format array.

To measure, define( 'SAVEQUERIES', true ) and read $wpdb->queries at the end of a request, or open Query Monitor, which lists each query with its time and calling function.

Worked example

A plugin's dashboard widget loads in 5 seconds. Query Monitor shows one call, $wpdb->get_results( "SELECT * FROM {$wpdb->postmeta} WHERE meta_key = 'views'" ), returning 190,000 rows and taking 4.2 seconds. The widget only displays the top 5.

The developer changes it to an ORDER BY ... LIMIT 5 query on a numeric cast and caches the result in a transient for 10 minutes. The widget now loads in 90 ms.

How it differs

wpdb reads the table prefix from the configuration and uses it to build table names, so $wpdb->posts is wp_posts on one site and xk7_posts on another. It runs whatever SQL you give it, but it is not a safety layer. A prepared statement through $wpdb->prepare() is how you pass user input in.

Common errors

Hard-coding wp_ in table names. Selecting all columns when you need one. Running queries inside loops. Reading $wpdb->last_error and ignoring it. Using $wpdb->query() with string concatenation of request data. Forgetting that on Multisite $wpdb->prefix changes with switch_to_blog().

In practice

Open Query Monitor on your slowest page and sort queries by time. Wrap the worst one in a proper query, add an index if needed, and cache the result. Replace any hard-coded prefix in your custom code with $wpdb properties.

See also

Table prefix, Prepared statement

Sources

Count this on a real site.

Watch my website