1

If someone opens any post at the front-end, does it matter how many times I call get_post_meta function? I thought it could increase performance if I won't call that function 2-3 times instead of 20 calls on single post page.

3

One call to get_post_meta() fetches all met keys and values for that post. All these values are then stored in the cache. The next call will just fetch the data from the cache. So you can safely call that function multiple times.

In details:

  1. get_post_meta() calls get_metadata('post', $post_id, $key, $single);
  2. get_metadata() checks the cache and calls update_meta_cache() if it doesn't find an existing cache.
  3. update_meta_cache() fetches all entries with:

    "SELECT $column, meta_key, meta_value 
     FROM $table 
     WHERE $column IN ($id_list) 
     ORDER BY $id_column ASC"
    

The same is true for user meta values.

|improve this answer|||||
  • so, if i call get_post_meta('smth'); then it also stored in cache all other keys (not only smth), right? wow, good. – T.Todua Nov 8 '16 at 20:10
1

...I thought it could increase performance if I won't call that function 2-3 times instead of 20 calls on single post page

Together with the excellent answer from @toscho, I will just add one additional thing, based on my latest digging.

If you don't set it otherwise WordPress queries will prefetch post meta values for all the posts the query returns.

This means even before you call get_post_meta(); the meta values are already in the WordPress cache.

Nacin, explained this and you can refer the slide 34 in this presentation.

enter image description here

From this image, you may understand that typically WordPress prefetches the information for the metadata and also for the terms.

The conclusion is the same as from @toscho. You may call get_post_meta(); whenever you need.


To get the basic details on how the caching looks, you also may check this post.

|improve this answer|||||

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.