Storing (multiple) selection field metadata

I'm having trouble saving the metadata included in a select box. Just an example (connected to the .php function on the single product setup page):

(...)


    <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%;" />

(...)

      

To save the data, I include in the .php function:

    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);
        }

        }

      

I get everything OK for the custom fields ("_ingrediente_x_quantidade"), but for the select field "_receita" I get an empty array:

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

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

      

What am I doing wrong? I'm new to coding!

+3


source to share


1 answer


I see one problem when storing data using foreach with the same key and post id for every record ...

Try to use this in base:



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

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

      

It would also be helpful to use validation for an empty array ...

0


source







All Articles