Get the SQL query generated by WordPress

One of the good things about WordPress is that it provides a nice abstraction to DB and you can query pretty much anything from the DB, by using the appropriate functions instead of writing the query yourself.

All though it is good, there are times when you want to see what was the actual SQL query that got generated. I faced this senarious myself, when I was debugging an issue in my Bulk Delete WordPress plugin.

It turns out that it is quite easy to do it.

The WP_Query object has a method called request that returns the SQL query that was generated.

So if you want to get the query generated by the global $wpdb object then you can use the following code

<?php echo $GLOBALS['wp_query']->request; ?>

On the other hand, if you are using a custom WP_Query object then you can call the request method on your object.

<?php
$my_query = new WP_Query();
echo $my_Query->request;
?>

Related posts

Tags: , ,

1 Comments so far

Follow up comments through RSS Feed | Post a comment

Leave a Reply

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