admin管理员组

文章数量:1390547

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.

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.

Share Improve this question asked Aug 21, 2011 at 20:35 FLXFLX 1,0273 gold badges17 silver badges31 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 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>

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.

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.

Similar to above I highly recommend query monitor plugin: https://wordpress/plugins/query-monitor/ It has a lot of great features and really helps with local debugging.

More professional tools to use are different APMs, but they come paid. The best one I ever worked with was new rellic, but datadog APM works quite good well.

本文标签: wp queryview queries made