user892134
user892134

Reputation: 3214

wordpress updating array in post meta

I'm having trouble updating an array in post meta. The array keeps overwriting instead of pushing in new values.

add_action('wp_ajax_update_item_received', 'update_item_received');

function update_item_received() {
$date = date('Y/m/d H:i'); 
$order_id = $_POST['order_id'];
$item_id = $_POST['item_id'];
$received_array = get_post_meta($order_id,"received_array");

if(is_array($received_array[0])) {
    //merge new with old

    $received_array_2[$item_id] = $date;
    array_merge($received_array[0],$received_array_2);
    update_post_meta($order_id,"received_array",$received_array);

} else {

    $received_array = array("$item_id"=>"$date");
    add_post_meta($order_id,"received_array",$received_array);

}

I use array_merge but the new array merging with the old. It becomes a multidimensional array?

How do i solve?

Upvotes: 2

Views: 282

Answers (1)

martynasma
martynasma

Reputation: 8595

get_post_meta() function returns post meta as array by default. If you know you will always have just one, use the third parameter true which means that it will return just a single meta item.

Then you can just add to it:

function update_item_received() {
  $date = date('Y/m/d H:i'); 
  $order_id = $_POST['order_id'];
  $item_id = $_POST['item_id'];
  $received_array = get_post_meta($order_id, "received_array", true);

  if(is_array($received_array)) {
      $received_array[$item_id] = $date;
      update_post_meta($order_id, "received_array", $received_array);
  } else {
      $received_array = array("$item_id"=>"$date");
      add_post_meta($order_id, "received_array", $received_array);
  }
}

Upvotes: 1

Related Questions