Buddypress: “Auto load” specific usermeta in WP?

WordPress already does this

When you fetch a user post or term WP will auto-fetch all of its meta and store it in WP Cache. This way if you need to use any of that post/term/users meta it’s already there. The thinking is to prefetch in bulk in a single query since it’s very rare that the meta isn’t used.

This way the data is fetched only once per request, but if you have a persistent object cache it can survive across requests leading to dramatic performance gains. In a best case scenario with an object cache and a well built site there may be no database queries at all.

If you look at the database queries with a tool such as Query Monitor you’ll see that additional calls to get_post_meta do not generate database queries.

The Exception

There is an exception though! If you decide to start fetching just post IDs to try and be efficient with your database calls, WordPress won’t pre-fetch these meta values, and it’ll generate a small database query when you try to use that raw user/post ID. As a result the optimisation of only fetching post IDs actually slow the site down!

Manually Priming Cache

In those cases such as above, you can fetch all post meta at once by using get_post_meta( $post_id ); or get_user_meta( $user_id ); and it’ll be returned as an array and cached. Likewise get_post and the user equivalent will prime caches, including terms.

But note that if you are using WP_Query or WP_User_Query normally, this is unnecessary, and in some circumstances may have a performance hit due to extra memory consumption or unnecessary checking.

Measure!

As with most performance, measure things and double check hard reality first. Unless you see firsthand lots of tiny queries, don’t try to optimise them away, especially if they’re not there to begin with.

A common beginner mistake is to implement something like WP Cache because they’re unaware of it, leading to an increased memory footprint and caching bugs with no measurable performance gains. Those that do see performance gains only see it as a reduction of the performance hit they received when they started requesting posts and users only have specific fields returned. Don’t request bespoke couture one of a kind results, request factory line standardised cachable results that can be churned out by the millions for every possible use case.