无法使用数组更新帖子元 [英] Can't update post meta using array
问题描述
我正在尝试使用 update_post_meta()
并保存来自数组.
I am trying to use update_post_meta()
and save a post meta from
Array.
示例:
$thing_to_add = array( '507' => 500, '366' => 550 );
update_post_meta($post_id, 'thing_to_add', $thing_to_add);
我想将整个 $ 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);
已解决::从下面的DavidWinder的评论中,我只是注意到它会自动序列化数组并将其保存在DB中.但是,它不会显示在帖子编辑页面上.
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.
推荐答案
请注意 update_post_meta 可以将数据保存为数组,但会自动序列化.
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.
在您的情况下:
<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
这篇关于无法使用数组更新帖子元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!