get_post_meta for all keys brings back arrays, not single values

$meta = get_post_meta($post_id,'',true);

brings back all the meta values for $post_id but it returns an array for each value, as shown below:
enter image description here

I might expect this if I had set the third parameter – single – to false but it’s set to true. I haven’t found anything in the codex that talks about what exactly is returned when key is blank.

Read More

Does someone have to information here and know how I can get back all the keys with each key value being a single value instead of an array of values?

Related posts

2 comments

  1. The answer is: This is by design, but does not appear to be documented in the Codex.

    If you look at the true documentation (the source code), you will see that get_post_meta calls get_metadata. By inspecting the code of get_metadata, we can see that if the $meta_key is not posted, then it returns the value before it evaluates if $single is set or not:

     // Previously, $meta_cache is set to the contents of the post meta data
    
     // Here you see if there is no key set, it just returns it all
     if ( ! $meta_key ) {
         return $meta_cache;
     }
    
     // It's not until later than $single becomes a factor
     if ( isset($meta_cache[$meta_key]) ) {
        if ( $single )
            return maybe_unserialize( $meta_cache[$meta_key][0] );
        else
            return array_map('maybe_unserialize', $meta_cache[$meta_key]);
     }
    

    If you are using PHP 5.3+, you can get what you want with something like this:

    // Get the meta values
    $meta = get_post_meta($post_id,'',true);
    
    // Now convert them to singles
    $meta = array_map(function($n) {return $n[0];}, $meta);
    

    Or, if you want to get really fancy, you can write your own “wrapper” around the get_post_meta function, like so:

    function get_all_post_meta($post_id) {
        // Get the meta values
        $meta = get_post_meta($post_id,'');
    
        // Now convert them to singles and return them
        return array_map(function($n) {return $n[0];}, $meta);
    }
    

    Which you could then use like so:

    $meta = get_all_post_meta($post_id);
    

    Or, if you aren’t on PHP 5.3+ (you should be!), you could do it like so:

    function get_all_post_meta($post_id) {
        // Get the meta values
        $meta = get_post_meta($post_id,'');
    
        foreach($meta AS $key => $value) {
            $meta[$key] = $value[0];
        }
    
        return $meta;
    }
    
  2. I think, there is no way to get single value in get_post_meta when $single is true. So you write a custom function to get it.

    Use

    //callback to get single value in get_meta_data
    function get_single_value($val) {
        return $val[0];
    }
    
    $meta = get_post_meta($post_id,'', true);
    $meta1 = array_map('get_postmeta_single_value', $meta);
    print_r($meta1);
    

Comments are closed.