Is it possible to print a log of all database requests for a page request in WordPress?

I create a plugin that executes a custom query in a WordPress database, and then I look at the results, listing each post header as a link to the actual post.

I use get_permalink($id) to get the URI of each message, but since I am doing this outside of the loop, my suspicion is each of these queries making a separate database request.

I checked the function code and tried to keep track of what is going on in the actual WordPress files, but what really interests me is the general way to do this, so I can make sure that I always write the most optimized code in all my plugins.

Does anyone know how best to do this?

+4
source share
2 answers

In wp-config.php add this line:

 define('SAVEQUERIES', true); 

In your topic, the functions.php file (or the plugin file, for that matter) you can use this:

 add_action('shutdown', 'sql_logger'); function sql_logger() { global $wpdb; $log_file = fopen(ABSPATH.'/sql_log.txt', 'a'); fwrite($log_file, "//////////////////////////////////////////\n\n" . date("F j, Y, g:i:sa")."\n"); foreach($wpdb->queries as $q) { fwrite($log_file, $q[0] . " - ($q[1] s)" . "\n\n"); } fclose($log_file); } 

Make sure that ABSPATH.'/sql_log.txt' written in PHP.

Hope this helps.

+16
source

Can't comment on @Poelinca Dorin's answer, so just stay here. If you want to know what triggers your request, just add this

fwrite($log_file, $q[0] . " - ($q[1] s)". " [Stack]: $q[2]" . "\n\n");

instead

fwrite($log_file, $q[0] . " - ($q[1] s)" . "\n\n");

0
source

Source: https://habr.com/ru/post/1335132/


All Articles