保存选择字段的(多个)元值

时间:2015-07-19 03:15:10

标签: php wordpress woocommerce

我无法保存“选择”字段框中包含的元数据。只是一个例子(将function.php挂钩到单个产品设置页面):

(...)


    <select style="width:100%" id="_receita" name="_receita[]" multiple="multiple" data-placeholder="<?php _e( 'Search for a product', 'woocommerce' ); ?>">
            <?php
                echo '<option value="TEST"> TEST </option>';
                echo '<option value="TEST1"> TEST1 </option>';
                echo '<option value="TEST2"> TEST2 </option>';
                ?>
            </select>

    // few others custom fields:
   <?php $ingrediente_x_quantidade = get_post_meta( $post->ID, '_ingrediente_x_quantidade', true ); ?>  
            <input placeholder="<?php _e( 'Ingrediente', 'woocommerce' ); ?>" type="text" class="ingrediente" id ="_ingrediente" name="_ingrediente" value="<?php echo $ingrediente_x_quantidade[0]; ?>" style="width: 90%;" />
            <input placeholder="<?php _e( 'qnt.', 'woocommerce' ); ?>" type="number" name="_quantidade" id="_quantidade" class = "quantidade" value="<?php echo $ingrediente_x_quantidade[1]; ?>" step="any" min="0" style="width: 25%;" />

(...)

要保存数据,我包括在function.php:

    add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );
    // Save Fields
    add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );


function woo_add_custom_general_fields_save( $post_id ){

// Custom Field
 $ingrediente_x_quantidade =  array( esc_attr( $_POST['_ingrediente'] ), esc_attr( $_POST['_quantidade'] ) );
 update_post_meta( $post_id, '_ingrediente_x_quantidade', $ingrediente_x_quantidade );

 // Select Field
 foreach ($_POST["_receita"] as $receita) {
 update_post_meta($post->ID, "_receita", $receita);
        }

        }

我为自定义字段(“_ingrediente_x_quantidade”)提供了一切正常,但是对于选择字段,“_ renceita”我得到一个空数组:

[_ingrediente_x_quantidade] => Array
(
[0] => a:2:{i:0;s:19:”Aveia, flocos, crua”;i:1;s:3:”113″;}
)

[_receita] => Array
(
[0] =>
)

我做错了什么?我对编码很新!

1 个答案:

答案 0 :(得分:0)

我发现使用foreach存储数据时存在一个问题,每个记录使用相同的密钥和帖子ID ...

尝试在base使用它:

update_post_meta($post->ID, "_receita", serialize($receita));

$receita = unserialize(get_post_meta($post->ID, "_receita", true));

使用对空数组的检查也很好......