Output the specific content of WordPress database query to reduce the number of database queries

Time:2020-1-14

Recently, I made a WordPress enterprise template and paid attention to the query times!

In footer.php, the following code is added to display the number of times WordPress queries the database and the query time:

<?php echo get_num_queries() . ‘ queries in ‘ . timer_stop(0) . ‘ seconds.’; ?>

The results showed that the first page was queried 30 times, and the log page was queried 45 times… It’s really depressing. In order to see what content of the database has been queried, Google got the following solutions, which are summarized here:

First, add the following code in wp-config.php:

define(‘SAVEQUERIES’, true);

Then add the following code in footer.php:

Copy code

The code is as follows:

<?php if (is_user_logged_in()){
global $wpdb;
echo “<pre>”;
print_r($wpdb->queries);
echo “</pre>”;
}? > analysis:

1. If (is ﹣ user ﹣ logged ﹣ in()) is used to determine whether the current visitor has logged in, or if (current ﹣ user ﹣ can (‘level ﹣ 10 ‘)) is used to determine whether the user has logged in as an administrator, so as not to let the tourists see the data, this code can be saved;

2. Global $wpdb; define the global variable $wpdb, which is the default database class of WordPress;

3. The results are nested in the HTML tag < pre >;

4. Print_r ($wpdb – > queries); output the information of each database query.

Refresh the homepage or log page, and you can see the output results similar to the following:

Copy code

The code is as follows:

Array
(
[0] => Array
(
[0] => SELECT SQL_CALC_FOUND_ROWS wp_posts.* FROM wp_posts WHERE 1=1 AND wp_posts.post_type = ‘post’ AND (wp_posts.post_status = ‘publish’ OR wp_posts.post_status = ‘private’) ORDER BY wp_posts.post_date DESC LIMIT 0, 10
[1] => 0.0003960132598877
[2] => require, wp, WP->main, WP->query_posts, WP_Query->query, WP_Query->get_posts
)
[1] => Array
(
[0] => SELECT option_value FROM wp_options WHERE option_name = ‘nuodou_header_code’ LIMIT 1
[1] => 0.0013589859008789
[2] => require, require_once, include, get_header, locate_template, load_template, require_once, get_option
)

… The following work has to be analyzed by yourself to see which can be deleted and which can be improved!

Recommended Today

What are the new methods of visual + map technology?

Last week, Ren Xiaofeng, chief scientist of Alibaba Gaode map, made a technical exchange with you on the development of computer vision related technology and the application in the field of map travel at the online live broadcast activity of “cloud dialogue” between senior students of Alibaba. The interaction between live broadcast is hot. Especially […]