How to Display and Debug All Database Queries Made by WordPress

qh7v 7 bqzi

When working with WordPress you will eventually have the question, “How do I display all database queries made by WordPress?”

In your wp-config.php file add the following:

define( 'SAVEQUERIES', true );

By setting SAVEQUERIES to true the wpdb global instance will store all the database queries you make; this will allow you to inspect the number of queries each page request makes to the database and the SQL used.

global $wpdb;
var_dump($wpdb->num_queries , $wpdb->queries);
  • $wpdb->queries: This will dump all SQL queires made to the database.
  • $wpdb->num_queries: This will give you the number of queries made to the database.

Also, WordPress has an official plugin to help debug and list SQL queries called the Debug Bar.

Helper Functions

I like to make functions to help with SQL debugging and general database tasks in WordPress.

/**
 * Get Database
 *
 * You may save all of the queries run on the database and their stop times by setting the
 * SAVEQUERIES constant to TRUE (this constant defaults to FALSE). If SAVEQUERIES is
 * TRUE, your queries will be stored in this variable as an array.
 *
 * @return wpdb $wpdb
 */
function wpdb() {
    global $wpdb;
    return $wpdb;
}

/**
 * Var Dump WordPress Database Queries
 */
function var_dump_database() {
    var_dump(wpdb()->num_queries , wpdb()->queries);
}

Implementing

In the functions.php file of your theme you will want to restrict the database information to Administrator users only. Also, you can choose to display the information if WP_DEBUG is true.

add_action('shutdown', function() {
   if(WP_DEBUG || current_user_can('administrator')) {
       var_dump_database();
   }
});

Dare To Code

icon send thick Get the tips, links, and tricks on full-stack PHP development in your inbox with monthly emails from Kevin Dees.

Name(Required)
This field is for validation purposes and should be left unchanged.

2 thoughts on “How to Display and Debug All Database Queries Made by WordPress

  1. After adding this to functions.php, the debug info shows up at the bottom of my main site, but I don’t see it in the /wp-admin administrator panel. Does one have to use a different hook other than “shutdown” to get this to work in the administrator panel?

Leave a Reply

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

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