skip to Main Content

When I echo $text I have this error array to string conversion.

How to solve this error?

function cd_meta_box_cb()
{
global $post;
$values = get_post_custom( $post->ID );
$text = isset( $values['video_meta_box_text'] ) ? $values['video_meta_box_text'] : '';
wp_nonce_field( 'video_meta_box_nonce', 'meta_box_nonce' );
?>
<p>

    <input type="text" name="video_meta_box_text" id="video_meta_box_text" value="<?php echo $text; ?>" />
</p>
<?php    
}

2

Answers


  1. Some types are converted to string when printing, such as integer, other types require some conversions in order to get a proper string output.

    To get a string output of your array you must convert it into a string by yourself.

    First, make sure $text will always be an array, even an empty one. There are other ways, but I’m keeping to this simple one.

    $text = isset( $values['video_meta_box_text'] ) ? $values['video_meta_box_text'] : [];
    

    Then you can use the implode() function to chain all the values into a single string.

    <input type="text" name="video_meta_box_text" id="video_meta_box_text" value="<?php echo implode(', ', $text); ?>">
    

    I’ve used a , delimiter here but you can you whatever suit you.

    Note that this way won’t work if your array contains values such as objects.

    Login or Signup to reply.
  2. Your data is saved in an array and you are trying to access it using only the array key.

    function cd_meta_box_cb() {
       global $post;
       $values = get_post_custom( $post->ID );
    
       //First, check to see if your array is not empty as it may still be set but without a value. Then return th efirst key of the array: [0]
       $text = !empty( $values['video_meta_box_text'] ) ? $values['video_meta_box_text'][0] : '';
       wp_nonce_field( 'video_meta_box_nonce', 'meta_box_nonce' );
    ?>
    <p>
    
       <input type="text" name="video_meta_box_text" id="video_meta_box_text" value=" <?php echo $text; ?>" /></p>
    <?php    
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search