Duplicate Database Queries Report for Administrators
Add ?wpide_queries=1 to any page while logged in as an administrator to see, at the bottom of the page, the queries that ran more than once and the ten slowest queries, with the code that called them.
Opens WPIDE on
Code
$wpide_enable_query_log = function () {
if ( isset( $_GET['wpide_queries'] ) && ! defined( 'SAVEQUERIES' ) && function_exists( 'wp_get_current_user' ) && current_user_can( 'manage_options' ) ) {
define( 'SAVEQUERIES', true );
}
};
if ( did_action( 'plugins_loaded' ) ) {
$wpide_enable_query_log();
} else {
add_action( 'plugins_loaded', $wpide_enable_query_log, 0 );
}
$wpide_query_report = function () {
global $wpdb;
if ( ! isset( $_GET['wpide_queries'] ) || ! current_user_can( 'manage_options' ) || empty( $wpdb->queries ) ) {
return;
}
$groups = array();
foreach ( $wpdb->queries as $q ) {
$sql = preg_replace( '/\s+/', ' ', trim( $q[0] ) );
if ( ! isset( $groups[ $sql ] ) ) {
$groups[ $sql ] = array( 'count' => 0, 'time' => 0.0, 'caller' => $q[2] );
}
$groups[ $sql ]['count']++;
$groups[ $sql ]['time'] += (float) $q[1];
}
$dupes = array_filter( $groups, function ( $g ) {
return $g['count'] > 1;
} );
uasort( $dupes, function ( $a, $b ) {
return $b['count'] <=> $a['count'];
} );
$slow = $wpdb->queries;
usort( $slow, function ( $a, $b ) {
return $b[1] <=> $a[1];
} );
echo '<div style="position:relative;z-index:99999;background:#fff;color:#1d2327;padding:16px;font:13px/1.5 monospace;border-top:4px solid #2271b1;">';
printf( '<p><strong>%s</strong></p>', esc_html( sprintf( '%d queries, %d duplicated statements.', count( $wpdb->queries ), count( $dupes ) ) ) );
echo '<p><strong>Duplicated queries</strong></p><ol>';
foreach ( array_slice( $dupes, 0, 25, true ) as $sql => $g ) {
printf( '<li>%s × %s <br><small>%s</small></li>', (int) $g['count'], esc_html( wp_html_excerpt( $sql, 300, '...' ) ), esc_html( $g['caller'] ) );
}
echo '</ol><p><strong>Slowest queries</strong></p><ol>';
foreach ( array_slice( $slow, 0, 10 ) as $q ) {
printf( '<li>%.4fs %s <br><small>%s</small></li>', (float) $q[1], esc_html( wp_html_excerpt( preg_replace( '/\s+/', ' ', $q[0] ), 300, '...' ) ), esc_html( $q[2] ) );
}
echo '</ol></div>';
};
add_action( 'wp_footer', $wpide_query_report, 9999 );
add_action( 'admin_footer', $wpide_query_report, 9999 );
Notes
Query logging only switches on for that one request, so normal visitors and pages are not slowed down.
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.