0

Is there any way to avoid that when you don’t specify a $key ('') and set $single to true in get_post_meta, it returns all keys still with an array of values, instead of returning a single value only .

$meta = get_post_meta(get_the_ID(), '', true);
print_r($meta);
//This is giving me:
//Array ( [key_1] => Array ( [0] => value_1 ), [key_2] => Array ( [0] => value_2 ) )
//And I will expect:
//Array ( [key_1] => value_1, [key_2] => value_2 )

I know that I can access the data writing array[key_1][0], but I don't understand why, considering that I'm declaring $single as TRUE.

I might be missing something...

0

get_post_meta() calls get_metadata(), the parameter description of which says:

$single (bool) (Optional) If true, return only the first value of the specified meta_key. This parameter has no effect if meta_key is not specified.

Default value: false

So, since you are passing '' as the meta_key, the $single parameter is ignored.

Does that explain it?

Edit:

If you only want the 1st value for each meta key, then just do the following:

array_map ('array_shift', get_post_meta (get_the_ID (), '')) ;
  • So, what should I do? Is there a way to get an array as desired: Array ( [key_1] => value_1, [key_2] => value_2 ) – Capiedge Mar 17 '17 at 22:46
  • OK, so there's no magic word for the second parameter of the function get_post_meta to achieve it... – Capiedge Mar 17 '17 at 23:12
  • that's correct. – Paul 'Sparrow Hawk' Biron Mar 17 '17 at 23:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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