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.

Continue reading “Easy way to collect all SQL queries in WordPress – with and without SAVEQUERIES enabled”

Getting the list of slow MySQL queries in WordPress

Saving MySQL queries is the part of WordPress Debug processes.
If the website works slowly, probably there are some problematic MySQL queries which can be from some plugin or your current theme. Without debugging we can’t know what happens under the hood.

If to define SAVEQUERIES constant in wp-config.php,  we can monitor all running queries in single process. To see that we can add simple code to our themes footer.php.  Here is how it looks like

wordpress mysql debug

But it might not be enough helpful if we can’t catch the problem in our testing process. We may not detect the problem in action, but the visitors still complain about it.  So what to do? Let’s keep SAVEQUERIES ON mode for some time and gather all slow queries for that period. At the end of this period we will be able to see all problematic queries and may be we will be able to solve them.

  1. Add this string to our wp-config.php : define( ‘SAVEQUERIES’, true );
  2. Add the code below to your theme’s footer.php. It will gather slow queries and save it to as WP Option data.
  3. After some time passed, check get_option(‘custom_mysql_debug’); value, it will show all slow MySQL queries in one string, one per line. Here is what it will look like.
    mysql-debug-result