Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm making a plugin that does a custom query on the WordPress database, and then I'm looping through the results listing each post title as a link to the actual post.

I'm using get_permalink($id) to obtain the URI of each post, but since I'm doing this outside of the loop, my suspicion is each of these requests is making a separate database query.

I've checked out the function code and tried to follow what's going on in the actual WordPress core files, but what I'm really interested in is a general way to do this, so I can make sure I'm always writing the most optimized code in all of my plugins.

Is anyone aware of the best way to accomplish this?

like image 512
Philip Walton Avatar asked Jan 11 '11 17:01

Philip Walton


People also ask

How do I print a query in WordPress?

To print sql queries in wordpress we use $wpdb object. The $wpdb object has some properties for this. Using $wpdb->last_query to print just the latest query executed, this is useful for debugging functions. Using a plugin like Query Monitor.

What are query logs?

The general query log is a general record of what mysqld is doing. The server writes information to this log when clients connect or disconnect, and it logs each SQL statement received from clients.


1 Answers

In wp-config.php add this line:

define('SAVEQUERIES', true);

In your theme functions.php file (or a 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:s a")."\n");
    foreach($wpdb->queries as $q) {
        fwrite($log_file, $q[0] . " - ($q[1] s)" . "\n\n");
    }
    fclose($log_file);
}

Make sure ABSPATH.'/sql_log.txt' is writeble from php.

Hope this helps.

like image 159
2 revs, 2 users 89% Avatar answered Sep 28 '22 05:09

2 revs, 2 users 89%