How to view the SQL query generated by WP_Query

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

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline
Inline