J'ai un metabox avec un tableau d'entrées:
<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 />
...
Et je le garde comme ça
update_post_meta( $post_id, "dates", $_POST['activite_dates'] );
Le problème est que lorsque je le récupère, je dois créer une fonction laide pour lire plusieurs tableaux de dimensions.
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
)
)
Et lorsque je l'enregistre, il ne fait qu'ajouter à ajouter à un tableau existant
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
)
)
Alors, premièrement, pourquoi ai-je 3 valeurs au premier niveau puis mon tableau est multiplié à l'intérieur du deuxième niveau?
Pour information voici mon code pour la vue:
$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
}
} ?>
Merci beaucoup !
<?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
}
} ?>