Write any database query that takes longer than 50 ms to the PHP error log, with the function that ran it.
add_action( 'shutdown', function (): void {
global $wpdb;
if ( ! defined( 'SAVEQUERIES' ) || ! SAVEQUERIES || empty( $wpdb->queries ) ) {
return;
}
$threshold = 0.05; // Seconds.
$url = esc_url_raw( $_SERVER['REQUEST_URI'] ?? '' );
foreach ( $wpdb->queries as $query ) {
[ $sql, $time, $caller ] = $query;
if ( $time >= $threshold ) {
error_log( sprintf(
'[slow query] %.3fs %s | %s | %s',
$time,
$url,
$caller,
preg_replace( '/\s+/', ' ', substr( $sql, 0, 500 ) )
) );
}
}
} );
Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.
A slow page is often caused by one or two slow database queries, usually from a plugin. This snippet records them so you can find out which code is responsible.
When SAVEQUERIES is on, WordPress records every query with its run time and the chain of functions that called it. At the end of the request, on shutdown, the snippet goes through that list and writes anything over the threshold to the error log.
The log line includes the time, the page URL, the caller and the start of the SQL.
define( 'SAVEQUERIES', true ); to wp-config.php to turn it on, and remove it when you’re done. Saving every query uses extra memory on every request.Turn on SAVEQUERIES, set the threshold to 0 and load a page. Your error log should list its queries. Then set it back to 0.05.