21

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?

2 Answers 2

57

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks! This is exactly what I was looking for. I actually modified the function a bit since I was actually looking to have the query list printed out at the bottom of each page, but I wouldn't have figured it out without your example.
Thanks @Poelinca, I also have same question, But using that method I get only the SELECT queries, but not the INSERT/UPDATE queries. Any solution for this? Is it possible?
You can also just use WordPress's debug.log file instead of writing to a new file: pastebin.com/jDKbmSDQ Just make sure you have define( 'WP_DEBUG', true ); in wp-config.php.
I suggest to use for log file content uploads directory instead, that is writable. $log_file = fopen(trailingslashit(WP_CONTENT_DIR) . 'uploads/sql_log.txt', 'a');
I'd suggest NOT hard coding 'uploads/sql_log.txt'. If 'UPLOADS' is defined, root/uploads may not exist, may not be writable. Better to use wp_upload_dir(). ''' $upload_dir = wp_upload_dir(); $upload_dir = $upload_dir['basedir'] $log_file = fopen(trailingslashit($upload_dir) . 'sql_log.txt', 'a'); Ref: developer.wordpress.org/reference/functions/wp_upload_dir
5

Can't comment on @Poelinca Dorin's answer, so I'll just say it here:

If you want to know what is launching your query just use this:

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

instead of:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.