Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?


share|improve this question

5 Answers 5

up vote 52 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.

share|improve this answer

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

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

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;
share|improve this answer

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

share|improve this answer
Wow, that's great, thanks! –  ramayac Sep 4 '12 at 22:28


Processing Queries with PL/SQL Processing a SQL query with PL/SQL is like processing files with other languages. For example, a Perl program opens a file, reads the file contents, processes each line, then closes the file. In the same way, a PL/SQL program issues a query and processes the rows from the result set as shown in Example 1-5.

Example 1-5 Processing Query Results in a LOOP

  FOR someone IN (SELECT * FROM employees WHERE employee_id < 120 )
    DBMS_OUTPUT.PUT_LINE('First name = ' || someone.first_name ||
                         ', Last name = ' || someone.last_name);
share|improve this answer
No, there is a specific wordpress function that can output the SQL code that was used to run a loop for example. I need this function. –  Keith Donegan Dec 3 '10 at 2:27

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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