I have an array saved in postmata, each array key become a metakey. I want to change the code to save the whole array with one metakey. How to do that? Thanks!

$poddata = Array(
'pod_id' => $this->pod_id,
'url' => $this->url,
'name' => $this->name,
'description' => $this->description,
'service' => $this->service,
'status' =>$this->status,
'price' => $this->price
);

foreach ( $poddata as $k => $v ){

if ( get_post_meta( $this->id, $k ) == '' )
add_post_meta( $this->id, $meta_box, $v, true );

elseif ( $v != get_post_meta( $this->id, $k, true ) )
update_post_meta( $this->id, $k, $v );

elseif ( $v == '' )
delete_post_meta( $this->id, $k, get_post_meta( $this->id, $k, true ) );

}
up vote 22 down vote accepted

You don't need to loop through the values. Just use update_post_meta($post_ID, {key}, {array of vals}), it should do!

<?php
$poddata = Array(
    'pod_id' => $this->pod_id,
    'url' => $this->url,
    'name' => $this->name,
    'description' => $this->description,
    'service' => $this->service,
    'status' =>$this->status,
    'price' => $this->price
    );

//Update inserts a new entry if it doesn't exist, updates otherwise
update_post_meta($post_ID, 'poddata', $poddata);
?>

Thats it! When you fetch it for usage, do the following:

    $poddata = get_post_meta($post_ID, 'poddata');

$poddata is the array of values.

  • I tried update_post_meta($post_ID, 'poddata', $postdata), after save the post, i see the meta is not saved. – Jenny Aug 6 '11 at 8:49
  • oh, sorry, It saved, I didn't see it on WP Custom Fields Table. I just found it in phpAdmin. Thanks! – Jenny Aug 6 '11 at 8:59
  • When retrive the data, by get_post_meta($post_ID, 'poddata'); I get array(0) from var_dump. How can I get the whole array? – Jenny Aug 6 '11 at 9:28
  • You're welcome! Try using print_r()... echo "<pre>"; print_r($poddata); echo "</pre>"; – Rutwick Gangurde Aug 6 '11 at 9:30
  • print_r($poddata) shows Array() – Jenny Aug 6 '11 at 9:47

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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