0

I am trying to get metadata for a post (of custom post type). I had a look in the database, and the table "wp_postmeta" holds a row with "post_id" = 65, "meta_key" = "name_text" and "meta_value" = "Lars Åkerkvist".

I am trying to fetch that value, Lars Åkerkvist, using get_post_meta as below

get_post_meta(65,"name_text",true)

But it always returns a 0. What am i doing wrong here?

2
  • First thing, you probably want to get your accept rate up or people will be disinclined to answer your question, you have 7 questions with 0 accepted answers between them, which doesn't bode well for you. Secondly, 0 is not a valid return from get_post_meta() unless it is the value which is stored in there. It returns an empty string on failure.
    – mor7ifer
    May 22, 2012 at 15:53
  • That was really bad of me, i must have forgot that... May 22, 2012 at 16:37

1 Answer 1

1

Change $single back to false, e.g.:

<?php $name_text = get_post_meta( 65, 'name_text' ); ?>

Why?

If set to true then the function will return a single result, as a string. If false, or not set, then the function returns an array of the custom fields. This is not intuitive. For example, if you fetch a serialized array with this method you want $single to be true to actually get an unserialized array back. If you pass in false, or leave it out, you will have an array of one, and the value at index 0 will be the serialized string.

You want to return the array, and then use $name_text[0].

2
  • I tried that now, but ran into a weird issue. If i do print_r on $name_text, i get the following result Array ( [0] => Anton Gildebrand ) 1 But if i do it like this $name_text[0], i get a 0 only May 22, 2012 at 16:38
  • Sorry my bad. I had accidently used the plus sign instead of dots when concatenating strings... May 22, 2012 at 16:40

Your Answer

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

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