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
Get the tips, links, and tricks on full-stack PHP development in your inbox from me: Kevin Dees.
"*" indicates required fields
Leave a Reply