如何在postmeta中使用一个metakey保存数组?


17

我有一个保存在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 ) );

}

Answers:


25

您不需要遍历这些值。只需使用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是值的数组。


我尝试了update_post_meta($ post_ID,'poddata',$ postdata),在保存帖子后,我看到未保存元。
珍妮

哦,很抱歉,它保存了,但是我在WP Custom Fields Table上没有看到它。我刚刚在phpAdmin中找到了它。谢谢!
珍妮

检索数据时,通过get_post_meta($ post_ID,'poddata'); 我从var_dump获得array(0)。我如何获得整个阵列?
珍妮

别客气!尝试使用print_r()... echo“ <pre>”; print_r($ poddata); 回声“ </ pre>”;
罗特威克·冈古德

print_r($ poddata)显示Array()
珍妮
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.