问题描述

我有一个数组保存在 postmata,每个数组键成为一个 metakey 。我想更改代码以使用一个元标记来保存整个数组。怎么做?谢谢!

$poddata = Array(
'pod_id' => $this->pod_id,
'url' => $this->url,
'name' => $this->name,
'description' => $this->description,
'service' => $this->service,
'status' =>$this->status,
'price' => $this->price
);

foreach ( $poddata as $k => $v ){

if ( get_post_meta( $this->id, $k ) == '' )
add_post_meta( $this->id, $meta_box, $v, true );

elseif ( $v != get_post_meta( $this->id, $k, true ) )
update_post_meta( $this->id, $k, $v );

elseif ( $v == '' )
delete_post_meta( $this->id, $k, get_post_meta( $this->id, $k, true ) );

}

最佳解决方案

您不需要循环遍历值。只要使用 update_post_meta($post_ID, {key}, {array of vals}),应该做!

<?php
$poddata = Array(
    'pod_id' => $this->pod_id,
    'url' => $this->url,
    'name' => $this->name,
    'description' => $this->description,
    'service' => $this->service,
    'status' =>$this->status,
    'price' => $this->price
    );

//Update inserts a new entry if it doesn't exist, updates otherwise
update_post_meta($post_ID, 'poddata', $poddata);
?>

而已!当您抓取它用于使用时,请执行以下操作:

    $poddata = get_post_meta($post_ID, 'poddata');

$ poddata 是值的数组。

参考文献

注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。