Log WordPress Database Queries
If you want to debug / log WordPress database queries, you have to enable SAVEQUERIES in wp-config.php:
define( 'SAVEQUERIES', true );
After enabling SAVEQUERIES, add this code to your functions.php or a plugin:
add_action( 'shutdown', function () {
global $wpdb;
$log_stack = true;
$log_file = fopen( ABSPATH . '/wp-content/sql.log', 'a' );
fwrite( $log_file, PHP_EOL . PHP_EOL . "############################################################" . PHP_EOL . PHP_EOL . date( "F j, Y, g:i:s a" ) . PHP_EOL );
foreach ( $wpdb->queries as $query ) {
fwrite( $log_file, $query[0] . " - ($query[1] s)" );
if ( $log_stack ) {
fwrite( $log_file, PHP_EOL . "[Stack]: $query[2]" . PHP_EOL . PHP_EOL );
} else {
fwrite( $log_file, PHP_EOL . PHP_EOL );
}
}
fclose( $log_file );
} );
This method will create a file wp-content/sql.log and log all your database queries there.