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...

1 Answer 1

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 (), '')) ;
3
  • 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
    Commented Mar 17, 2017 at 22:46
  • OK, so there's no magic word for the second parameter of the function get_post_meta to achieve it...
    – Capiedge
    Commented Mar 17, 2017 at 23:12
  • that's correct. Commented Mar 17, 2017 at 23:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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