0

I am a complete newbie at PHP so please forgive me. I am wanting to display some data in the following format:

"Post name" - "Custom Field String (in this case, 'custom_date')"

I am currently using the following PHP code

$output .= $indent . '<li id="item_'.$page->ID.'"><span>'.apply_filters( 'the_title', $page->post_title, get_post_meta($post->ID,'item_',TRUE), $current_custom_date = $page->$custom_date ) .' - ' . $current_custom_date . '</span>';

The title and the dash are displaying perfectly. However, the Custom Field String is just displaying "Array" so now looks like this.

"Post name" - Array

How would I get this to display the custom_date correctly? I've already set get_post_meta to 'true' as you can see so that shouldn't be the problem.

0

Setting the third parameter of get_post_meta to true does not guarantee that you get a string. What that parameter does is control how many rows of the database get returned. When true you only get a single result and not an array of all of the rows in the database that match. You will get a single value but it will only be a string if you've saved a string to the database. If you've saved an array, you will still have an array.

There is a note in the Codex about this:

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.

http://codex.wordpress.org/Function_Reference/get_post_meta

It sounds like that is what is happening. The data associated with your item_ key is an array (serialized) in the database and so it is still an array even though it is a "single" result. I can't with confidence tell you how to retrieve that but it should be something like:

$my_meta = get_post_meta($post->ID,'item_',TRUE);
echo $my_meta[0]; // or
echo $my_meta['some_key']; 

In the context of your code you wouldn't need the echo because you are using the string not printing it.

| improve this answer | |
  • Thanks. You're right. A few lines below that indicate that posts is either saved as an array or grabbed as an array: ` foreach( $values as $position => $id ) { $wpdb->update( $wpdb->posts, array('menu_order' => $position, 'post_parent' => str_replace('item_', '', $key)), array('ID' => $id) ); }`. Now I just need to figure out how to grab them as strings. Any ideas? – Bravo315 Aug 9 '13 at 14:01
  • You can't "grab" them as strings, not directly from the database. You just use the keys of the array (or a loop) to extract the part of the array as a string. The two echo lines demonstrate that. – s_ha_dum Aug 9 '13 at 14:43

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.