Is it possible to update the dataset using update_post_meta

I am trying to create two custom fields for image and text.
I have two inputs in the loop:

...
<input type="hidden" name="wt_set['upload_set_img'][]" id="img" value="100" />
<input type="text" name="wt_set['title'][]" value="Text One" />

<input type="hidden" name="wt_set['upload_set_img'][]" id="img1" value="200" />
<input type="text" name="wt_set['title'][]" value="Text Two" />
...

The result is this $_POST[‘wt_set’]

array(2) {
  ["upload_set_img"]=>
  array(2) {
    [0]=>
    string(3) "100"
    [1]=>
    string(3) "200"
  }
  ["title"]=>
  array(2) {
    [0]=>
    string(3) "Text One"
    [1]=>
    string(3) "Text Two"
  }
}

Then I do this:

foreach( $_POST['wt_set'] as $name => $arr_values ){
    foreach( $arr_values as $i => $value){
        update_post_meta( $post_id, $name, $value );
    }
}

But I only get one value:

  ["upload_set_img"]=>
  array(1) {
    [0]=>
    string(3) "100"
  }
  ["title"]=>
  array(1) {
    [0]=>
    string(4) "Text One"
  }

I need get_post_meta($post->ID,'upload_set_img'); and get_post_meta($post->ID,'title'); equaled:

["upload_set_img"]=>
  array(1) {
    [0]=>
    string(3) "100"
    [1]=>
    string(3) "200"
  }
  ["title"]=>
  array(1) {
    [0]=>
    string(4) "Text One"
    [1]=>
    string(4) "Text Two"
  }

How do I properly use update_post_meta to get this result?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You don’t need your second foreach loop.

foreach( $_POST['wt_set'] as $name => $val ){
    update_post_meta( $post_id, $name, $val );
}

What’s happening is with your second foreach is each entry is being processed individually and set as the post meta, so as it’s looping through it’s running update_post_meta( $post_id, $name, XXX ); then update_post_meta( $post_id, $name, XXX ); which overrides the previous one.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x