I have come across a function before that displayed the exact SQL code that was used in a loop for example, but can't remember.

Can anybody tell me that function?


up vote 125 down vote accepted

Hi @Keith Donegan:

If I understand your question correctly I think this is what you are looking for?

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

$wp_query is a global variable that contains the current query run by the loop. If you run the above code anytime while the loop is still active or even right after the loop it should give you the SQL from the loop. Just make sure you inspect it before letting something else run that uses query_posts() again.

  • How to get queries of $wpdb? $GLOBALS['wpdb']->request not working – mpsbhat Jan 21 '17 at 5:24
  • Works even on custom query, $my_query = new WP_Query([ /* ...some args... */ ]); => $my_query->request – jave.web Aug 16 '17 at 12:26

If you ran a query based on WP_Query, it's this:

$customPosts = new WP_Query($yourArgs);
echo "Last SQL-Query: {$customPosts->request}";

If you are only interested in Loops this is what I usually use:

add_filter( 'posts_request', 'dump_request' );

function dump_request( $input ) {


    return $input;

See this answer: Best Collection of Code for your functions.php file

Then add ?debug=sql to any WP URL, and it'll output the full list of queries that were run. (And yes, it's scary...)

  • 3
    Wow, that's great, thanks! – ramayac Sep 4 '12 at 22:28

Your Answer


By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.