user10640643
user10640643

Reputation:

Can't update post meta using array

I am trying to use update_post_meta() and save a post meta from Array.

Example:

$thing_to_add = array( '507' => 500, '366' => 550 );
update_post_meta($post_id, 'thing_to_add', $thing_to_add);

I want to save the whole $thing_to_add in my post meta, but it is not saving it . If $thing_to_add is a string, it updates. But I want to save the array. How can I do that?

I've included my full code below.

<input type="number" name="inventory_id[507]" />
<input type="number" name="inventory_id[366]" />
$inventory_ids = $_POST['inventory_id'];
//var_dump shows this - array(2) { [507]=> string(2) "500" [366]=> string(2) "550" }
update_post_meta($post_id, 'inventory_ids', $inventory_ids);

Solved: From DavidWinder's comment below, I just noticed it automatically serializes the array and saves it in DB. However it doesn't show on post edit page.

Upvotes: 2

Views: 1464

Answers (1)

dWinder
dWinder

Reputation: 11642

Notice that update_post_meta can save data as array but it is automatically serialized.

If you want to get the value back as array you should use the flag $single of the get_post_meta.

In your case:

<input type="number" name="inventory_id[507]" />
<input type="number" name="inventory_id[366]" />
$inventory_ids = $_POST['inventory_id'];

//var_dump shows this - array(2) { [507]=> string(2) "500" [366]=> string(2) "550" }

// save the meta
update_post_meta($post_id, 'inventory_ids', $inventory_ids);

// get the meta
$inventory_ids_from_meta = get_post_meta( $post_id, 'inventory_ids', true ); // this is the true flag

Upvotes: 2

Related Questions