phpwordpress

Textbox string custom meta value gets saved, but after save it's shown as "array"


I'm setting up a custom meta box for the page editor. The values entered into the text fields save correctly and are visible in the custom fields box. But after updating, the text fields in the custom meta box all display the word "Array" instead of the text string that was saved.

screenshot

Here's the code from the functions.php

function restaurant_meta_box_cb()
{        
    global $post;
    $values = get_post_custom( $post->ID );

    $text_name = isset( $values['biz_name'] ) ? $values['biz_name'] : '';
    $text_addr = isset( $values['biz_addr'] ) ? $values['biz_addr'] : '';

    // We'll use this nonce field later on when saving.
    wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' );
    ?>
    <p>
        <label for="biz_name">Restaurant Name</label>
        <input type="text" name="biz_name" id="biz_name" value="<?php echo $text_name; ?>" />
    </p>
    <p>
        <label for="biz_name">Address</label>
        <input type="text" name="biz_addr" id="biz_addr" value="<?php echo $text_addr; ?>" />
    </p>

    <?php    
}

Solution

  • get_post_custom always returns a multidimensional array, even if expecting array of single values - Ref Codex: get_post_custom

    So even though you have (presumably) set up biz_name and biz_addr as strings, get_post_custom() will still return each value in an array.

    As you know for sure that it will have only 1 single result, you can just access the first element directly, e.g.

    $text_name = isset( $values['biz_name'][0] ) ? $values['biz_name'][0] : '';
    $text_addr = isset( $values['biz_addr'][0] ) ? $values['biz_addr'][0] : '';
    


    FYI: Unrelated to your problem, but I noticed you have the wrong for value in your Address label (it should be "biz_addr"): <label for="biz_name">Address</label>