WordPress: How to view the SQL query generated by WP_Query

October 12, 2012

WP_Query is a magical object in WordPress. WP_Query allows you to quickly and easily build a query for any type of object in the database, however that power is also sometimes its downfall. WP_Query adds “magic” into the SQL query it generates. If you are at your wits end with everything looking right when you pass it to WP_Query you may want to print out the SQL string WP_Query built and check it for mistakes or odd “magic” fields/restrictions/etc that may have been put into it. You can do so with the WP_Query request property. The following is an example of how you might use said property:

$query_args = array(
// Imagine a big list of complex arguments here

$results = new WP_Query( $query_args );
// Oops, $results has nothing, or something we did not expect
// Show the query
echo $results->request;

Having access to the actual SQL query string being sent to the database can be powerful and a life saver.

9 thoughts on “WordPress: How to view the SQL query generated by WP_Query

  1. mcartur (June 5, 2013)

    Thanks¡¡ It was clear and useful

  2. Chris Dillon (December 20, 2013)

    Thanks. This helped me solve a pesky sql_mode problem. I’m wondering why it’s not in the codex.

    1. Ben Lobaugh (blobaugh) (December 20, 2013)

      Codex is an open wiki. Maybe it should be added if it is useful 🙂

  3. Tommy Johnson (January 10, 2014)

    The angels are singing! Now that I know what the query is, I can see plain as day why things aren’t working. Thanks for this bit of info!

    1. Ben Lobaugh (blobaugh) (January 10, 2014)

      Glad it helped Tommy! I posted it due to the exact same frustration. Happy it helps people 🙂

  4. chetan (November 23, 2014)

    very useful object of wordpress. thanx for suggest.

  5. Robert (July 11, 2015)

    Thanks! Now I know why I keep getting the darn “Sorry, no posts matched your criteria.”

  6. Gerry (September 30, 2015)

    Hi thanks for post. But when I do this I get:
    DBG: result.request=SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = ‘job_listing’ AND ((wp_posts.post_status = ‘publish’)) GROUP BY wp_posts.ID ORDER BY wp_posts.menu_order ASC, wp_posts.post_date DESC LIMIT 0, 10

  7. Nick (September 22, 2016)

    Thx mate