2

I know I can use get_num_queries() for the number of queries. However, how can I see what queries Wordpress actually makes? I've tried using $query but that didn't work.

7

See this codex page.

in wp-config.php:

define('SAVEQUERIES', true);

then in your template:

if (current_user_can('administrator')){
    global $wpdb;
    echo "<pre>";
    print_r($wpdb->queries);
    echo "</pre>";
}

or without the above SAVEQUERIES, you can still see just the main query:

global $wp_query;
echo $wp_query->request;

or to see all of $wp_query:

<pre>
    <?php print_r($wp_query); ?>
</pre>
  • This is useful and the results are shocking, I can't understand why Wordpress makes soooo many useless queries – JasonDavis Apr 21 '12 at 20:49
0

Milo's answer is right on. I would add that to save you some trouble, download the WordPress Debug Bar plugin. This plugin will add a little bar to the bottom of your front end pages and it will capture important debugging information, including queries made during the request. For it to work you need to make sure that the constants WP_DEBUG and SAVE_QUERIES are set to true in your wp-config.php file.

0

There is another low level way of finding out what queries have been made throughout a request which was very useful for me in order to identify what was being inserted into the database upon submitting a form.

Basically what I did was one database dump before submitting the form, another database dump after submitting the form, then a diff of the two.

Although it may look too primitive, the result was exactly what I needed, without having to install any plugins or modify any code or wp-config.php.

The procedure I adopted was:

  1. Get the form ready to submit, with all fields filled.

  2. Do the first dump (change user, pass and dbname accordingly):

    mysqldump -uuser -ppass dbname --skip-opt > /tmp/before.sql

  3. Submit the form.

  4. Do the second dump (change user, pass and dbname accordingly):

    mysqldump -uuser -ppass dbname --skip-opt > /tmp/after.sql

  5. Compare before.sql and after.sql, analyzing the result in vim:

    diff /tmp/before.sql /tmp/after.sql | vim -

Very useful for generating users migration scripts, for example.

Notes:

  1. --skip-opt generates a dump with one SQL instruction per line, so it's easier to see the changes when you run diff.

  2. | vim - makes vim read the output of diff directly into its buffer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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