UPDATE_POST_META上的多个条目

时间:2013-02-18 作者:Jonathan Lafleur

我有一个包含输入数组的元盒:

<input type="text" name="activite_dates[]" size="30" /><br />
<input type="text" name="activite_dates[]" size="30" /><br />
<input type="text" name="activite_dates[]" size="30" /><br />
...
我就这样保存着

update_post_meta( $post_id, "dates", $_POST[\'activite_dates\'] );
问题是,当我检索它时,我必须生成一个丑陋的函数来读取多维数组

Array 
(
[0] => Array
    (
        [0] => DATA1
        [1] => DATA2
        [2] => DATA3
        [3] => DATA99
    )

[1] => Array
    (
        [0] => DATA1
        [1] => DATA2
        [2] => DATA3
        [3] => DATA99
    )

[2] => Array
    (
        [0] => DATA1
        [1] => DATA2
        [2] => DATA3
        [3] => DATA99
    )
()

当我保存它时,它只是添加到现有数组中

Array 
(
[0] => Array
    (
        [0] => DATA1
        [1] => DATA2
        [2] => DATA3
        [3] => DATA99
        [4] => DATA1
        [5] => DATA2
        [6] => DATA3
        [7] => DATA99
    )

[1] => Array
    (
        [0] => DATA1
        [1] => DATA2
        [2] => DATA3
        [3] => DATA99
        [4] => DATA1
        [5] => DATA2
        [6] => DATA3
        [7] => DATA99        
     )

[2] => Array
    (
        [0] => DATA1
        [1] => DATA2
        [2] => DATA3
        [3] => DATA99
        [4] => DATA1
        [5] => DATA2
        [6] => DATA3
        [7] => DATA99
    )

)
那么首先,为什么我在第一级有3个值,然后我的数组在第二级内相乘?

有关信息,请参阅我的视图代码:

$dates_gf = get_post_meta( $object->ID, \'dates\', false );
foreach ($dates_gf as $date_gf) {
    if (is_array($date_gf)){
        foreach ($date_gf as $arr_date_gf) {
            ?> <input type="text" name="activite_dates_gf[]" value="<?php echo $arr_date_gf; ?>" size="30" /><br /> <?php
        }
    } else {
        ?> <input type="text" name="activite_dates_gf[]" value="<?php echo $date_gf; ?>" size="30" /><br /> <?php
    }
} ?>
非常感谢!

1 个回复
最合适的回答,由SO网友:Cole 整理而成
<?php
// Check to make sure array is ready
if( isset($_POST[\'activite_dates\']) && is_array($_POST[\'activite_dates\']) ) {
    // If we have an array ready to save delete all the previous data
    delete_post_meta( $post_id, "dates");
    foreach($_POST[\'activite_dates\'] as $date) {
        // Use add post meta instead of passing the array directly in
        add_post_meta( $post_id, "dates", esc_attr($date));
    }
}



$dates_gf = get_post_meta( $object->ID, \'dates\', false );

// No need for the is_array() check when using false for the $single variable. Check for empty() instead
if(!empty($dates_gf)) {
    foreach($dates_gf as $date_gf) {
        ?> <input type="text" name="activite_dates_gf[]" value="<?php echo $date_gf; ?>" size="30" /><br /> <?php
    }
} ?>
结束

相关推荐

为什么esc_url在SmartMetabox中不起作用

你试过吗http://www.wproots.com/ultimate-guide-to-meta-boxes-in-wordpress/ ? 创建metabox是一个很好的类。但我对验证有问题。我试过了sanitize_callback 参数来清理URL,所以我使用esc_url 但该字段仍然接受所有值。这里有什么问题?这是我的密码add_smart_meta_box( \'themename_slides_url\', array( \'title\' => _