我在很多地方看到 WordPress 会自动使用 update_post_meta 序列化数组。
但是,他们的文档指出您应该在使用 update_post_meta 之前对其进行序列化。 https://developer.wordpress.org/reference/functions/update_post_meta/
当使用使用序列化值或数组的 get_post_meta 时,我也得到不同的结果。
$val = array();
$val['one'] = 1;
$val['two'] = 2;
$val['threed']['x'] = 'ex';
$val['threed']['y'] = 'why';
$ser = serialize($val);
update_post_meta($order_id, 'testing arr', $val);
update_post_meta($order_id, 'testing ser arr', $ser);
// This was saved in the table as...
// a:3:{s:3:"one";i:1;s:3:"two";i:2;s:6:"threed";a:2:{s:1:"x";s:2:"ex";s:1:"y";s:3:"why";}}
// s:88:"a:3:{s:3:"one";i:1;s:3:"two";i:2;s:6:"threed";a:2:{s:1:"x";s:2:"ex";s:1:"y";s:3:"why";}}";
$testarr = get_post_meta($order_id, 'testing arr');
$testarrser = get_post_meta($order_id, 'testing ser arr');
Using get_post_meta for each of the above and printing the array gives the following:
NOTE 1: get_post_meta($id, $field, true) and get_post_meta($id, $field, false) return the same data structure.
NOTE 2: These were not unserialized - just print_r() the returned values.
testarr: Array(
[0] => Array (
[one] => 1
[two] => 2
[threed] => Array (
[x] => ex
[y] => why
)
)
)
testarrser: Array(
[0] => a:3:{s:3:"one";i:1;s:3:"two";i:2;s:6:"threed";a:2:{s:1:"x";s:2:"ex";s:1:"y";s:3:"why";}}
)
Please explain the correct way to update_post_meta to retrieve the expected array.
不,在使用 WordPress
add_post_meta()
或 update_post_meta()
函数之前,您不需要序列化数组,因为这些函数会自动执行此操作。
现在使用
get_post_meta()
时,将第三个参数设置为true
以获得正确的初始保存数组,例如
$testarr = get_post_meta($order_id, 'testing arr', true);
注意:
对于 WooCommerce 订单,您不应再使用 WordPress 帖子元功能,而是应使用
WC_Order
对象中的 CRUD 方法,例如:
$data = array();
$data['one'] = 1;
$data['two'] = 2;
$data['threed']['x'] = 'ex';
$data['threed']['y'] = 'why';
$order = wc_get_order( $order_id ); // Get the WC_Order Object (if needed)
$order->update_meta_data( 'testing_arr', $data ); // Add the metadata
$order->save(); // Save it to the database
要从 WC_Order 对象获取此数组,请使用:
$order = wc_get_order( $order_id ); // Get the WC_Order Object (if needed)
$data = $order->get_meta('testing_arr'); // Get the metadata
这种方式与高性能订单存储 (HPOS) 兼容,因为 WooCommerce 现在使用数据库中的自定义表。
相关: