Run Custom SQL Queries in WordPress with $wpdb->prepare and get_results

Run custom SQL queries in WordPress with $wpdb->prepare() and get_results()

WP_Query covers most needs, but some queries it cannot express or makes inefficient: aggregations with GROUP BY, joins across several tables, bulk updates. For those, WordPress gives the $wpdb object, a direct connection to the database, with $wpdb->prepare() for safe parameters.

Problem: Run an aggregation, a complex join or a bulk update against the WordPress database safely, when WP_Query cannot do it.

Solution: Write the SQL with the table names from $wpdb ($wpdb->posts, $wpdb->prefix), pass every value through prepare() placeholders, and choose the method by the result you need.

The methods

  • get_results( $sql, $output ): all rows; objects by default, ARRAY_A for associative arrays, ARRAY_N for numeric ones;
  • get_row(): one row; get_col(): one column of all rows; get_var(): one value;
  • query(): INSERT, UPDATE, DELETE; returns the number of affected rows or false;
  • insert(), update(), delete(): the same for one table without writing SQL, with the escaping done for you.

prepare() uses printf-style placeholders: %s for strings, %d for integers, %f for floats. Do not put quotes around them: prepare() adds them for strings.

Examples

<?php
global $wpdb;

// 1. Published posts per category: an aggregation
$cat_counts = $wpdb->get_results( $wpdb->prepare(
    "SELECT t.name, t.slug, COUNT(p.ID) AS post_count
     FROM {$wpdb->terms} t
     INNER JOIN {$wpdb->term_taxonomy} tt ON tt.term_id = t.term_id
     INNER JOIN {$wpdb->term_relationships} tr ON tr.term_taxonomy_id = tt.term_taxonomy_id
     INNER JOIN {$wpdb->posts} p ON p.ID = tr.object_id
     WHERE tt.taxonomy = %s AND p.post_status = %s AND p.post_type = %s
     GROUP BY t.term_id
     ORDER BY post_count DESC
     LIMIT %d",
    'category', 'publish', 'post', 20
), ARRAY_A );

// 2. The latest post of every author: a correlated subquery
$latest_per_author = $wpdb->get_results(
    "SELECT p.post_author, p.ID, p.post_title, p.post_date
     FROM {$wpdb->posts} p
     WHERE p.post_type = 'post' AND p.post_status = 'publish'
       AND p.post_date = (
           SELECT MAX(p2.post_date) FROM {$wpdb->posts} p2
           WHERE p2.post_author = p.post_author AND p2.post_type = 'post' AND p2.post_status = 'publish'
       )
     ORDER BY p.post_date DESC"
);

// 3. Set a meta value for all posts of one category: a bulk update
$updated = $wpdb->query( $wpdb->prepare(
    "UPDATE {$wpdb->postmeta} pm
     INNER JOIN {$wpdb->term_relationships} tr ON tr.object_id = pm.post_id
     INNER JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id
     SET pm.meta_value = %s
     WHERE tt.term_id = %d AND pm.meta_key = %s",
    'reviewed', 42, '_review_status'
) );

if ( false === $updated ) {
    error_log( 'Bulk update failed: ' . $wpdb->last_error );
}

The second query has no external values, so it does not need prepare(). The third one changes only existing rows: posts that do not have the _review_status meta yet are not affected.

After a direct write

WordPress caches posts, meta and terms in the object cache. A direct UPDATE bypasses it, so with a persistent cache (Redis, Memcached) the old values stay visible. Clear what you changed: clean_post_cache( $post_id ) for each post, or wp_cache_flush() after a big batch.

Debugging

$wpdb->last_error holds the last MySQL error, $wpdb->last_query the last query. define( 'SAVEQUERIES', true ); in wp-config.php records every query with its time in $wpdb->queries; use it only on a test site, it costs memory on every request. To see how MySQL runs your query, put EXPLAIN in front of it.

NOTE: Never build SQL by concatenating input, even on admin screens: an admin account can be compromised, and a $_GET parameter on an admin page is still controlled by whoever sends the link. When the queries are against wp_postmeta and get slow, a custom table with dbDelta is usually the next step.