在 wp_postmeta 中将自定义字段数据保存为正确的序列化数组格式

Saving custom fields data as right serialized array format in wp_postmeta

我正在使用 woocommerce 开发 wordpress,并将 WCK plugin 用于自定义字段。我正在以编程方式创建产品。

我需要以编程方式将自定义字段数据保存为数据库中的数组。但它没有正确保存,也没有在产品后端显示自定义字段值。我正在使用此代码。

 $data= array(
    'alternative-product-names' => $alternative_pname,
    'manufacturers-part-number' => $manufature_park_number,
    'currently-packaged'=> $currently_packaged,
    'other-package-options' => $other_pkg_opt,
    'inner-pack-qty' => $inner_pack_qty,
    'inner-pack-dimensions' => $inner_pck_dimension,
    'packaging-picture'=>''
    );

update_post_meta( $post_id, 'productextrainfo1234', $data );

我需要以这种格式保存数据:

a:1:{i:0;a:15:{s:25:"alternative-product-names";s:4:"fgfg";s:25:"manufacturers-part-number";s:4:"gffg";s:18:"currently-packaged";s:4:"fgfg";s:21:"other-package-options";s:4:"fgfg";s:14:"inner-pack-qty";s:4:"fggf";s:21:"inner-pack-dimensions";s:17:"packaging-picture";s:3:"561";}}

测试您的代码后:

First, as you have 7 lines of key/values in your array, so your serialized string can't begin with a:1:{i:0;a:15:{ … but instead with a:1:{i:0;a:7:{ ….

Second, You need to embed your array in an empty array to get the correct format like you want:
a:1:{i:0;a:7:{ … }};.

所以你的代码必须是这样的:

$data= array( 
    array(
        'alternative-product-names' => $alternative_pname,
        'manufacturers-part-number' => $manufature_park_number,
        'currently-packaged'        => $currently_packaged,
        'other-package-options'     => $other_pkg_opt,
        'inner-pack-qty'            => $inner_pack_qty,
        'inner-pack-dimensions'     => $inner_pck_dimension,
        'packaging-picture'         => ''
    )
);

update_post_meta( $product_id, 'productextrainfo1234', $data );

通过这种方式,您将在数据库中获得此​​序列化数据值:

a:1:{i:0;a:7:{s:25:"alternative-product-names";N;s:25:"manufacturers-part-number";N;s:18:"currently-packaged";N;s:21:"other-package-options";N;s:14:"inner-pack-qty";N;s:21:"inner-pack-dimensions";N;s:17:"packaging-picture";s:0:"";}}

而不是:

a:7:{s:25:"alternative-product-names";N;s:25:"manufacturers-part-number";N;s:18:"currently-packaged";N;s:21:"other-package-options";N;s:14:"inner-pack-qty";N;s:21:"inner-pack-dimensions";N;s:17:"packaging-picture";s:0:"";}