How to display SQL query that ran in query?

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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

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

Method 3

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

Method 4

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;
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x