[wp-hackers] Best way to do user caching

Simon Blackbourn piemanek at gmail.com
Fri Jun 11 20:29:45 UTC 2010


A while ago I noticed that sites with posts by many different users can
generate huge numbers of database queries. [1]

Michael Pretty suggested using the cache_users function (new in 3.0). I've
now incorporated this into my site but thought I'd write to the list a) to
check if this is the best way to do it, and b) so anyone else can use the
code if it's helpful to them.

I've put the following into functions.php:

function my_cache_users() {

    global $wp_query;

    $users = array();

    foreach ( $wp_query->posts as $post ) {
        if ( !in_array( $post->post_author, $users ) ) {
            $users[] = $post->post_author;
        }
    }

    cache_users( $users );

}

I call it from the template file just before the loop starts.

It certainly does the job for me (database queries down from over 110 to
10), but if there are any suggestions for a better way please let me know.

Cheers
Simon

[1]
http://groups.google.com/group/wp-hackers/browse_thread/thread/b0482e2bc82cb76e/


More information about the wp-hackers mailing list