Does get_post_meta() makes a separate query to the database?

Viewed 232

A question of mine which I had to ask a long time ago.. I am curious if these wordpress functions like get_post_meta makes a sql query to the database or does it is loaded in WP_Query global variable when page is loaded? Thank you

1 Answers

get_post_meta() is a wrapper for get_metadata() and get_metadata() uses the global WP_Object_Cache object.

The relevant code is:

function get_metadata( $meta_type, $object_id, $meta_key = '', $single = false ) {
   ...
    $meta_cache = wp_cache_get( $object_id, $meta_type . '_meta' );

    if ( ! $meta_cache ) {
        $meta_cache = update_meta_cache( $meta_type, array( $object_id ) );
        if ( isset( $meta_cache[ $object_id ] ) ) {
            $meta_cache = $meta_cache[ $object_id ];
        } else {
            $meta_cache = null;
        }
    }
    ...
}

where wp_cache_get() is checking the global WP_Object_Cache object $wp_object_cache and update_meta_cache() is updating the global WP_Object_Cache object $wp_object_cache if the data is not in the cache. Of course this update requires a SQL query.

Incidentally, the global WP_Object_Cache object $wp_object_cache is used for much more than post meta data - it is a generic cache and WordPress and plugins uses it for caching values that are expensive to recompute.

Related