0

I have a directory website and am doing a bit of a redesign/restructure. I have quite a few meta fields for each entry, i.e. address, city, country, website, where to buy their products, social links, background and so on.

I don't display all the meta data in the same place in my layout. So my question: Is it more efficient to use get_post_meta($id,$key,false) and have all my meta values stored in a $variable, or is it better to get each individually?

I would assume it is the former, but wanted to get some feedback.

2
  • Can I say both of you answered this question?
    – dkmojo
    Jul 2, 2013 at 15:41
  • ^^ No. You can't "accept" both. Pick the one you think is best, accept it, and upvote one or both if the answer deserves it.
    – s_ha_dum
    Jul 2, 2013 at 15:43

2 Answers 2

1

Assuming you're retrieving the posts using a standard WP_Query in some manner, then the postmeta data is automatically retrieved for all the relevant posts and cached in memory. When you later call get_post_meta, the data is simply returned from here.

So honestly, it doesn't make any significant difference which approach you take. The get_post_meta function isn't making database calls unless the data isn't in memory already.

If you're making a WP_Query and have no need to cache the postmeta info, you can set the update_post_meta_cache argument in the query to false. Similarly, you can set the update_post_term_cache to false to prevent it from caching relevant terms from the taxonomy system as well. These can speed up a query for specific cases where you know that you don't need the meta/terms in advance.

1
  • Thanks! Yes I am performing this in a standard WP_Query. In my category.php and single.php templates. I do need a little bit of meta in category template. Good to know about the meta cache. I should have known this, DOH!
    – dkmojo
    Jul 2, 2013 at 15:39
1

If you look at the function that actually retrieves the metadata, you will notice that there is a built in caching mechanism, and all of the meta for the object is retrieved and cached, or so that function reads to me.

The performance difference between the two approaches should therefore be insignificant. Do what works best for your code. I tend to prefer putting everything into a variable but only because I very frequently use loops to generate the output.

1
  • Cool, thanks for the link. Since I will be displaying certain meta data above and below the post content and based on category(ies) the post is assigned to I'll probably call each individually within separate methods, i.e. contact_info, social_inks etc and display them as I need to. Thanks for your help!
    – dkmojo
    Jul 2, 2013 at 15:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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