Wordpress - Count & Display Database Queries

You can paste this block of code in your currently active WordPress theme functions.php file:

function wpse_footer_db_queries(){
    echo '<!-- '.get_num_queries().' queries in '.timer_stop(0).' seconds. -->'.PHP_EOL;
}
add_action('wp_footer', 'wpse_footer_db_queries');

The above block of code, will render an HTML comment in the footer of your theme (before </body> and </html>, containing the number of database queries and how log they took to retrieve.


Add …

define( 'SAVEQUERIES', TRUE );

… to your wp-config.php, and inspect $wpdb->queries at shutdown. That is the latest hook and the only one after which no queries are fired. Plus, it works on wp-admin/ too.

Sample code as a plugin:

<?php
/**
 * Plugin Name: T5 Inspect Queries
 * Description: Adds a list of all queries at the end of each file.
 *
 * Add the following to your wp-config.php:

define( 'WP_DEBUG',         TRUE );
define( 'SAVEQUERIES',      TRUE );

 */

add_action( 'shutdown', 't5_inspect_queries' );

/**
 * Print a list of all database queries.
 *
 * @wp-hook shutdown
 * @return  void
 */
function t5_inspect_queries()
{
    global $wpdb;

    $list = '';

    if ( ! empty( $wpdb->queries ) )
    {
        $queries = array ();
        foreach ( $wpdb->queries as $query )
        {
            $queries[] = sprintf(
                '<li><pre>%1$s</pre>Time: %2$s sec<pre>%3$s</pre></li>',
                nl2br( esc_html( $query[0] ) ),
                number_format( sprintf('%0.1f', $query[1] * 1000), 1, '.', ',' ),
                esc_html( implode( "\n", explode(', ', $query[2] ) ) )
            );
        }

        $list = '<ol>' . implode( '', $queries ) . '</ol>';
    }

    printf(
        '<style>pre{white-space:pre-wrap !important}</style>
        <div class="%1$s"><p><b>%2$s Queries</b></p>%3$s</div>',
        __FUNCTION__,
        $wpdb->num_queries,
        $list
    );
}

Update

After thinking a little bit longer about it I have written another plugin more suited for my needs – and probably yours if you prefer the console.

<?php
/**
 * Plugin Name: T5 Log Queries
 * Description: Writes all queries to '/query-log.sql'.
 * Plugin URI:  http://wordpress.stackexchange.com/a/70853/73
 * Version:     2012.11.04
 * Licence:     MIT
 */

add_filter( 'query', 't5_log_queries' );

/**
 * Write the SQL to a file.
 *
 * @wp-hook query
 * @param   string $query
 * @return  string Unchanged query
 */
function t5_log_queries( $query )
{
    static $first = TRUE;
    // Change the path here.
    $log_path = apply_filters(
        't5_log_queries_path',
        ABSPATH . 'query-log.sql'
    );
    $header = '';

    if ( $first )
    {
        $time    = date( 'Y-m-d H:i:s' );
        $request = $_SERVER['REQUEST_URI'];
        $header  = "\n\n# -- Request URI: $request, Time: $time ------------\n";
        $first   = FALSE;
    }

    file_put_contents( $log_path, "$header\n$query", FILE_APPEND | LOCK_EX );

    return $query;
}

Track the file with tail (available on Windows if Git is installed):

$ tail -f query-log.sql -n 50