Slow Database Query Warning for Admins
When SAVEQUERIES is enabled, lists the slowest database queries of the page with their duration and caller in an HTML comment visible to administrators.
Opens WPIDE on
Code
add_action( 'wp_footer', function () {
global $wpdb;
$limit = 10; // Number of slowest queries to list.
if ( ! defined( 'SAVEQUERIES' ) || ! SAVEQUERIES || ! current_user_can( 'manage_options' ) || empty( $wpdb->queries ) ) {
return;
}
$queries = $wpdb->queries;
usort( $queries, function ( $a, $b ) {
return $b[1] <=> $a[1];
} );
$lines = array( sprintf( 'Slowest %d of %d queries', min( $limit, count( $queries ) ), count( $queries ) ) );
foreach ( array_slice( $queries, 0, $limit ) as $query ) {
$lines[] = sprintf( '%.4fs | %s | %s', $query[1], preg_replace( '/\s+/', ' ', mb_substr( $query[0], 0, 300 ) ), $query[2] );
}
echo "\n<!--\n" . esc_html( str_replace( '--', '- -', implode( "\n", $lines ) ) ) . "\n-->\n";
}, 9999 );
Notes
Add define( 'SAVEQUERIES', true ); to wp-config.php while debugging only; it slows the site down. Change $limit to show more queries.
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.