WordPress – Get the SQL Query Used by get_posts()

The get_posts() function in WordPress retrieves an array of posts matching the parameters provided by the programmer. Thus, it's one of the most important and useful functions of WordPress, since posts are quite often at the heart of any WordPress website. The results of any query to the function can obviously be seen by examining the output, but sometimes it's really helpful to examine the SQL query actually created by get_posts().

There are WordPress plugins which you may find useful (one such is Query Monitor) in studying the SQL statements which your site generates, but sometimes this is overkill, and sometimes they don't do quite what you need.

Initially, one might think that using $GLOBALS['wp_the_query'], or global $wp_query, or $GLOBALS['wp_query'] is the way to go. However, one soon learns that the get_posts() function creates its own instance of WP_Query inside the get_posts() function. Of course, this instance of WP_Query does not override the global $wp_query, and the localized version is already out of scope by the time you need to query it. Thus when you go to use $wp_query it will contain a completely different query to what you were expecting.

Get the SQL Query Used by get_posts()

So, what to do? Well, the quick and dirty way that I did this, for debugging purposes, and avoiding anything more complex than adding just a few of lines that could easily be commented out afterwards, was as so:

// some other code up here ...

get_posts( array('tag_id' => $tag_id, 'post__not_in' => $negs) ); # $negs is an array

// --- DEBUGGING ---

// create a new WP_Query object with the args above
$args = array('tag_id' => $tag_id, 'post__not_in' => $negs);
$wpq = new WP_Query($args);
$my_query = $wpq->request;

// --- END DEBUGGING ---

// output $my_query to wherever you like

// program carries on ...

So, we're not actually changing the way that the get_posts function is doing anything, or adding code to functions.php or anything like that. We simply create a new WP_Query object, and using the arguments provided to the original query, we make the same request to our own object ($wpq) and then get the SQL back in $my_query.

For me this did exactly what I wanted and I was easily able to see the same SQL query that had been used by get_posts(). This works fine for simple debugging, although you may want to investigate other methods if your needs are more complex or substantial.

Also, remember to comment out or delete your debugging code once you've finished with it.

I hope someone may find the method provided above useful for their own debugging!