List Every Database Query on a Page for Administrators
When SAVEQUERIES is enabled, lets administrators add ?wpide_queries=1 to a front-end URL to see every SQL query of the page with its time and calling function, slowest first.
Opens WPIDE on
Code
add_action( 'wp_footer', function () {
global $wpdb;
if ( ! isset( $_GET['wpide_queries'] ) || ! current_user_can( 'manage_options' ) ) {
return;
}
if ( ! defined( 'SAVEQUERIES' ) || ! SAVEQUERIES ) {
if ( empty( $wpdb->queries ) ) {
echo '<p style="margin:2rem;padding:1rem;background:#fff;color:#1d2327;border:1px solid #c3c4c7">Enable SAVEQUERIES in wp-config.php to log queries.</p>';
return;
}
}
$queries = (array) $wpdb->queries;
usort( $queries, function ( $a, $b ) {
return $b[1] <=> $a[1];
} );
$total = array_sum( array_column( $queries, 1 ) );
echo '<details open style="margin:2rem;padding:1rem;background:#fff;color:#1d2327;border:1px solid #c3c4c7;font:12px/1.5 monospace;position:relative;z-index:99999;overflow:auto">';
printf( '<summary><strong>%d queries in %s ms</strong></summary><table style="width:100%%;border-collapse:collapse">', count( $queries ), esc_html( number_format_i18n( $total * 1000, 1 ) ) );
foreach ( $queries as $query ) {
$callers = array_map( 'trim', explode( ',', (string) $query[2] ) );
printf(
'<tr style="border-top:1px solid #eee;vertical-align:top"><td style="padding:4px;white-space:nowrap">%s ms</td><td style="padding:4px"><code style="white-space:pre-wrap">%s</code><br><small style="color:#646970">%s</small></td></tr>',
esc_html( number_format_i18n( $query[1] * 1000, 2 ) ),
esc_html( $query[0] ),
esc_html( end( $callers ) )
);
}
echo '</table></details>';
}, PHP_INT_MAX );
Notes
Add define( 'SAVEQUERIES', true ); to wp-config.php while debugging only, as it uses extra memory on every request.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.