update_meta_cache

Update the metadata cache for the specified objects.

Description

(array|false) update_meta_cache( (string) $meta_type, (int|array) $object_ids ); 

Returns (array|false)

Metadata cache for the specified objects, or false on failure.

Parameters (2)

0. $meta_type (string)
Type of object metadata is for (e.g., comment, post, or user)
1. $object_ids (int|array)
Array or comma delimited list of object IDs to update cache for

Usage

  1. if ( !function_exists( 'update_meta_cache' ) ) { 
  2. require_once ABSPATH . WPINC . '/meta.php'; 
  3.  
  4. // Type of object metadata is for (e.g., comment, post, or user) 
  5. $meta_type = ''; 
  6.  
  7. // Array or comma delimited list of object IDs to update cache for 
  8. $object_ids = null; 
  9.  
  10. // NOTICE! Understand what this does before running. 
  11. $result = update_meta_cache($meta_type, $object_ids); 
  12.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/meta.php  
  1. function update_meta_cache($meta_type, $object_ids) { 
  2. global $wpdb; 
  3.  
  4. if ( ! $meta_type || ! $object_ids ) { 
  5. return false; 
  6.  
  7. $table = _get_meta_table( $meta_type ); 
  8. if ( ! $table ) { 
  9. return false; 
  10.  
  11. $column = sanitize_key($meta_type . '_id'); 
  12.  
  13. if ( !is_array($object_ids) ) { 
  14. $object_ids = preg_replace('|[^0-9, ]|', '', $object_ids); 
  15. $object_ids = explode(', ', $object_ids); 
  16.  
  17. $object_ids = array_map('intval', $object_ids); 
  18.  
  19. $cache_key = $meta_type . '_meta'; 
  20. $ids = array(); 
  21. $cache = array(); 
  22. foreach ( $object_ids as $id ) { 
  23. $cached_object = wp_cache_get( $id, $cache_key ); 
  24. if ( false === $cached_object ) 
  25. $ids[] = $id; 
  26. else 
  27. $cache[$id] = $cached_object; 
  28.  
  29. if ( empty( $ids ) ) 
  30. return $cache; 
  31.  
  32. // Get meta info 
  33. $id_list = join( ', ', $ids ); 
  34. $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id'; 
  35. $meta_list = $wpdb->get_results( "SELECT $column, meta_key, meta_value FROM $table WHERE $column IN ($id_list) ORDER BY $id_column ASC", ARRAY_A ); 
  36.  
  37. if ( !empty($meta_list) ) { 
  38. foreach ( $meta_list as $metarow) { 
  39. $mpid = intval($metarow[$column]); 
  40. $mkey = $metarow['meta_key']; 
  41. $mval = $metarow['meta_value']; 
  42.  
  43. // Force subkeys to be array type: 
  44. if ( !isset($cache[$mpid]) || !is_array($cache[$mpid]) ) 
  45. $cache[$mpid] = array(); 
  46. if ( !isset($cache[$mpid][$mkey]) || !is_array($cache[$mpid][$mkey]) ) 
  47. $cache[$mpid][$mkey] = array(); 
  48.  
  49. // Add a value to the current pid/key: 
  50. $cache[$mpid][$mkey][] = $mval; 
  51.  
  52. foreach ( $ids as $id ) { 
  53. if ( ! isset($cache[$id]) ) 
  54. $cache[$id] = array(); 
  55. wp_cache_add( $id, $cache[$id], $cache_key ); 
  56.  
  57. return $cache;