Easy way to collect all SQL queries in WordPress – with and without SAVEQUERIES enabled

As we know WordPress has built in DB class called WPDB and all SQL queries should run via that class.

And in WordPress Debugging the only way to collect/debug executed SQL queries is activating debug constant called SAVEQUERIES.

And this constant forces WPDB to collect all SQL queries – but to display or save those queries we need to use some custom function.

Q: Where to run that function?

A: Usually it is recommended to add saving function to wp_footer hook – simply because wp_footer runs after most processes are finished. (and admin_footer for wp_admin)

But this is totally wrong! Why? Just because wp_footer runs in template side and doesn’t include some processes such as AJAX processes.

So we need to use another hook for that.

Here are 2 simple ways to catch all SQL queries of WPDB.

  1. Shutdown Hook.
  2. Using hook filter from WPDB class.

Shutdown Hook.

add_action('shutdown', function(){
	if (current_user_can('administrator')){
		ob_start();
		global $wpdb;
		print_r($wpdb->queries);
		$results=ob_get_clean();
		file_put_contents('/path/to/log/file', 
                date('y-m-d H:i:s').PHP_EOL.$results,FILE_APPEND);
	}
});

Using filter from WPDB class.

This way saves queries to the file one by one. This is great if you want to track some related event before it runs. (FYI, SAVEQUERIES collects all queries and prints all together, at the end.)

add_filter('query', 'query_saver_for_wpdb');

function query_saver_for_wpdb($sql){
     if (current_user_can('administrator')){
                $results=$sql;
                $results.=': '.PHP_EOL.
                wp_debug_backtrace_summary( __CLASS__ ).' - '.
                PHP_EOL. date('Y-m-d H:i:s').PHP_EOL;
	        file_put_contents('/path/to/log/file', 
                date('y-m-d H:i:s').PHP_EOL.$results,FILE_APPEND);
	}
        return $sql;
}

That’s all. Of course you can adjust these actions and save important queries only. (for example, you can add “string contains” condition and to save the queries which contains some tablename, string.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.