Blog / WordPress/ Display SQL Query Count in WordPress Footer

Display SQL Query Count in WordPress Footer

WordPress在底部添加SQL查询次数

For a well-optimized WordPress theme, fewer SQL queries generally indicate better performance. How can you see how many SQL queries were executed during the current page load?

This guide shows how to display the SQL query count at the bottom of your WordPress pages.

How to Implement

Add the following code snippet to an appropriate location in your theme (e.g., at the end of your footer.php file) to display the SQL query count in the page footer.

<?php if (current_user_can('manage_options')) : ?>
<div id="sql-query-count" style="text-align: center; font-size: 12px; color: #666; margin: 20px 0;">
    This page executed <?php echo get_num_queries(); ?> SQL queries.
</div>
<?php endif; ?>

Code Explanation & Best Practices

1. Permission Check: The code uses current_user_can('manage_options') to conditionally display the count. Only site administrators (or users with the 'manage_options' capability) will see it, preventing exposure to regular visitors.

2. Function Explanation: get_num_queries() is a core WordPress function that returns the total number of SQL queries executed during the current page load.

3. Placement: It's recommended to add this code to your theme's footer.php file, just before the closing </body> tag. Consider using a child theme or a code snippet plugin to avoid losing the modification during theme updates.

4. Performance Monitoring: This number helps you assess the performance of your theme and plugins. A well-optimized site should typically have fewer than 100 SQL queries on the homepage (depending on feature complexity). An unusually high count may indicate a need to optimize plugins or custom queries.

Post a Comment

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