132

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?

4 Answers 4

165

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.

3
  • How to get queries of $wpdb? $GLOBALS['wpdb']->request not working
    – mpsbhat
    Commented Jan 21, 2017 at 5:24
  • 5
    Works even on custom query, $my_query = new WP_Query([ /* ...some args... */ ]); => $my_query->request
    – jave.web
    Commented Aug 16, 2017 at 12:26
  • it's very helpful Commented Mar 22, 2023 at 7:29
83

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

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

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

0
27

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

add_filter( 'posts_request', 'dump_request' );

function dump_request( $input ) {

    var_dump($input);

    return $input;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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