The get_num_queries() WordPress PHP function retrieves the number of database queries during the WordPress execution.
Usage
$num_queries = get_num_queries(); echo "Number of queries: " . $num_queries;
Parameters
- None
More information
See WordPress Developer Resources: get_num_queries()
Examples
Display Number of Queries on Footer
Display the number of database queries executed on your site’s footer.
function display_query_count_footer() {
$query_count = get_num_queries();
echo '<p>Number of queries: ' . $query_count . '</p>';
}
add_action('wp_footer', 'display_query_count_footer');
Log Queries to File
Log the number of database queries executed during WordPress execution to a log file.
function log_query_count() {
$query_count = get_num_queries();
$log_message = 'Number of queries: ' . $query_count . PHP_EOL;
error_log($log_message, 3, '/path/to/your/logfile.log');
}
add_action('shutdown', 'log_query_count');
Show Queries on Admin Dashboard
Display the number of database queries executed on the WordPress admin dashboard.
function show_query_count_dashboard() {
$query_count = get_num_queries();
echo '<p>Number of queries: ' . $query_count . '</p>';
}
add_action('admin_notices', 'show_query_count_dashboard');
Display Queries on Debug Bar
If the Debug Bar plugin is installed, add a panel to display the number of database queries.
function add_queries_panel($panels) {
$query_count = get_num_queries();
$panel_content = 'Number of queries: ' . $query_count;
$panels[] = new Debug_Bar_Panel($panel_content);
return $panels;
}
add_filter('debug_bar_panels', 'add_queries_panel');
Alert if Queries Exceed Threshold
Send an email alert if the number of database queries exceeds a defined threshold.
function alert_query_count() {
$query_count = get_num_queries();
$threshold = 100;
if ($query_count > $threshold) {
$to = '[email protected]';
$subject = 'High Query Count Alert';
$message = 'Number of queries: ' . $query_count;
wp_mail($to, $subject, $message);
}
}
add_action('shutdown', 'alert_query_count');