Ben Lobaugh Online

I think, therefore I am. I am, therefore I sail

WordPress: How to view the SQL query generated by WP_Query

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.


WordPress: Basic checklist when setting up a new site


Recap of 2012 WordCamp Vancouver ( WCYVR )


  1. mcartur

    Thanks¡¡ It was clear and useful

  2. Chris Dillon

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

  3. 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!

  4. very useful object of wordpress. thanx for suggest.

  5. Robert

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

  6. 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

    Thx mate

Comments are closed.