avatar Deluxe Blog Tips About Projects

WordPress: How to get number of queries made by your code

When you need to know how performant your code is, one metric is how many queries to the database it makes.

While profiling plugins like Query Monitor give you a number of total queries and a number of queries created by components (themes, plugins), it's hard to know a how many queries a specific piece of code makes (for example: a specific function).

Without knowing this number of queries, you probably don't know where to optimize your code to make it run faster by making less queries. You might do the wrong optimization or optimize the wrong part of your code.

So, how do we know the number of queries that your code makes?

First, enable SAVEQUERIES in your wp-config.php like this:

define( 'SAVEQUERIES', true );

This constant tells WordPress to save all queries for future debugging and analyzing. In short, if you (or a plugin) make any query to the database, the global $wpdb will save it.

To get the number of queries that already made to the database, WordPress has a helpful function get_num_queries(). It simply get the number of queries saved in the $wpdb global variable.

By using get_num_queries() you can know how many queries that your code makes:

$num_queries_start = get_num_queries();  

// Run your code  
do_your_stuff_here();  

echo 'Number of queries: ', get_num_queries() - $num_queries_start;

The logic of the code is rather simple: you log the number of queries before and after running your code. The difference between them is the number of queries that you made.

If you want to have more details about your queries, then you can use this code:

// Run your code  
do_your_stuff_here();  

global $wpdb;  
echo '<pre>';  
print_r( $wpdb->queries );  
echo '</pre>';

This code outputs all the queries that have been made, which are stored in $wpdb->queries. You'll know the SQL query, time to perform that query and how many queries. It's very useful to see which is a slow query that need to be optimized.

🔥 HOT: Interested in boosting your WordPress SEO? My Slim SEO plugin is a super lighweight and automated plugin that handles most the hard work for you: meta tags, sitemap, redirection, schema & link building.

👉 Have a look and you will love it: wpslimseo.com

Comments