How to view the sql query generated by wp_query

$wp_query is a global variable that contains the current query run by the loop. WP_Query allows you to quickly and easily build a query for any type of object in the database. 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 WP_Query object has a method called request that returns the SQL query that was generated.The following is an example of how you might use this 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;

Leave a Comment

Scroll to Top