2

I'm trying to limit the number of database reads per page request. Currently, each time the get_avatar hook fires, I make a call to get_option() which returns some data. The $data returned doesn't change for the duration of the page request so I have many redundant calls to get_option() taking place (because get_avatar fires multiple times on some of my pages).

function my_check() {
    $data = get_option( 'blah' );
    return $data;
}

function my_func( $avatar, $id_or_email, $size, $default, $alt ) {
    if ( my_check() ) {
        // Do something.
    }
}
add_filter( 'get_avatar', 'my_func', 10, 5 );

My first thought was to use object-oriented PHP to make $data a class variable but I feel a class is overkill for this simple scenario. Then I thought about making $data a global variable, but then realised globals are bad. So I've ruled out these two approaches.

Is there another way I can make the $data variable available for the duration of the page request? My aim is to avoid multiple calls to get_option().

Note: The value of $data may change in-between page requests.

2

A class provides structure, and if it's what you need to do it then do it. The alternative would be a global variable, which is bad practice and should be avoided ( and makes reliable unit testing near impossible )

However, your entire premise is unnecessary. WordPress already stores the option in its caches, so no second database call occurs.

Otherwise yes, a class or object would be the answer

  • Does it store all options in cache by default? Even ones I add myself via add_option()? – henrywright Mar 11 '15 at 10:40
  • WP Cache persists for the duration of the request. The option is cached after the first time it's retrieved, birgires answer just changes how it's first loaded. If your server has an object cache you can make these persist between requests – Tom J Nowell Mar 11 '15 at 10:42
  • The autoload option is on by default, so my answer was not that useful ;-) @henrywright If you your objects are cached in the memory you should see the difference already. +1 – birgire Mar 11 '15 at 10:50
  • Thanks both for this info, it's been really helpful. I can see now that wp_cache_get() is used inside get_option(). – henrywright Mar 11 '15 at 10:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.