TL;DR: Add this code to your plugin/theme and it will log all SQL queries (warning it can be a lot, and will impact performance) to a queries.log
file in the current directory.
add_action(
'shutdown',
function() {
global $wpdb;
error_log( print_r( $wpdb->queries, true ), 3, dirname( __FILE__ ) . '/queries.log' );
}
);
And don’t forget to enable SAVEQUERIES
in wp-config.php
define( 'SAVEQUERIES', true );
I’ve been working A LOT with the WordPress REST API for a plugin I’m writing for work. Right now I’m working on tweaking the custom search functionality that is built into the plugin via REST API calls and to do so I’m doing a fair amount of copying WordPress generated SQL into Sequel Pro to do testing and debugging.
I was using XDebug breakpoints but got tired of having to start, stop, continue, and step through code to find the query I was working on, so I decided to see if I could just log all of the SQL queries somewhere so I could go through them at my leisure.
There is a fair amount of information on the web about using SAVEQUERIES
to log your queries to the Debug Bar among other places, but I wasn’t able to find a way to capture queries that were run using the REST API.
If you want you can just use error_log
and have the queries saved to the standard debug.log
in the wp-content/
folder, but I didn’t want to clutter that up. I also ran into the problem where print_r
kept outputting just 1
, I’d forgotten to set the second parameter to true
so PHP will just return the value instead of echoing it (which made for some very odd page displays)
Leave a Reply