How to log all SQL queries in WordPress

How do you get a complete log of the SQL queries done when a request is made? You could use a plugin for that, but sometimes it may be easier to a few lines of code and after the job is done, remove them.

In my case, I needed to know where some data, that comes from a custom options panel, in a third-party plugin, is saved. It was hard to find it in the code. So I ended up with a log of the SQL queries. Then I searched for UPDATE queries and found the table that was affected. That way I was able to find it and after that could create my own function that would use that data.

First of all, we need to define a constant that will force WordPress to save all queries.

Add the following code in wp-config.php

define('SAVEQUERIES', true);

Next, we need to save them somewhere. I’ll instruct it to save them in a file under the uploads folder. I choose uploads it because it already should be writable by WP.

Add the following code in the functions.php file of your active theme or in a custom plugin.

add_action('shutdown', 'mySqlLogger');
function mySqlLogger()
    global $wpdb;

    $file = fopen(trailingslashit(WP_CONTENT_DIR) . 'uploads/sqlLogs.txt', 'a');

    fwrite($file, "\n\n------ NEW REQUEST [" . date("F j, Y, g:i:s a") . "] ------\n\n");

    foreach ($wpdb->queries as $q) {
        fwrite($file, $q[0] . " - ($q[1] s)" . "\n\n");


Now if you reload a page, make an ajax request, or save something, all SQL requests will be saved in uploads/sqlLogs.txt

Simple like that!

Warning! Once you’ve found what you needed, make sure to remove this code from your theme/plugin. This should never run in a production environment. It’s intended only for development purposes.

Member since January 2, 2019

As a seasoned WordPress developer with expertise in various tech stacks and languages, I bring years of experience to every project I undertake. My passion for coding and dedication to delivering exceptional work ensures that every project I undertake is of the highest quality. I specialize in creating custom themes, developing plugins, and building full-scale web systems. By staying up-to-date with the latest industry trends and best practices, I am able to incorporate cutting-edge solutions into my work.


    Your email address will not be published. Required fields are marked *