开发者

How to display all database queries made by Wordpress?

Using a method similar to the one described here, I can see the total number of querie开发者_如何学JAVAs being made in Wordpress when I load a page.

Now I'd like to display all database queries that are being made when a page loads. This would allow me to see who my biggest resource hogs are, without having to go through the process of elimination of all my plugins and theme scripts.

What would be the best way to display all database queries made by Wordpress?


If you add define('SAVEQUERIES', true) to your configuration file, you can then list all the queries made for the current page by adding the following to your theme.

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

See the documentation for more details: http://codex.wordpress.org/Editing_wp-config.php#Save_queries_for_analysis


or you can hook into posts_request. You can put the coe inside functions.php such as

add_filter('posts_request','debug_post_request'); // debugging sql query of a post

function debug_post_request($sql_text) {

   $GLOBALS['debugku'] = $sql_text; //intercept and store the sql<br/>
   return $sql_text; 

}

in your theme footer, you can use print_r like

print_r($GLOBALS['debugku']);


Use Query Monitor.

It's a free and open-source plugin where you can filter your queries in various contexts, such as:

  • Which plugin called
  • Queries that took the most time
  • Duplicated queries
  • You can filter by Select / Update / Insert / Delete

Among other things...

How to display all database queries made by Wordpress?


I like to add at the bottom of the page, queries/elapsed time, here the code:

/**
 * show all sql at footer if it defined in wp-config.php:
 * define('SAVEQUERIES', true);
 */
function plg_name_show_debug_queries()
{
    if (defined('SAVEQUERIES') && SAVEQUERIES) {
        global $wpdb;
        if (is_array($wpdb->queries)) foreach ($wpdb->queries as $key => $q) {
            list($query, $elapsed, $debug) = $q;
            $time = number_format(($elapsed * 1000), 3);
            $count = $key + 1;
            $total_time += $elapsed;
            echo "
            <div style=\"position: relative; z-index: 9999    ; background: black; color: white; padding:10px\">
                $count - Query: $query <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Time: $time ms
            </div>";
        }
        echo "
        <div style=\"position: relative; z-index: 9999    ; background: black; color: white; padding:10px\">
            Total Queries: " . count($wpdb->queries) . "<br>Total Time: " . number_format(($total_time * 1000), 3) . " ms
        </div>";
    }
}
add_action('admin_footer', 'plg_name_show_debug_queries', PHP_INT_MAX);
add_action('wp_footer', 'plg_name_show_debug_queries', PHP_INT_MAX);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜