Working on a wordpress metabox-plugin and trying to save metadata as a multidimensional array (in text that i explode later on).
This is my code:
function wordpress_metabox() {
$event_adress = explode('|', get_post_meta($post->ID, '_event_adress', true));
foreach ($event_id as $key => $id){
echo '<div class="event">
<div class="ticket">
<input type="text" name="_event_adress[]" value="'.$event_adress[$key].'" />
<input type="text" name="_event_price[]" value="'.$event_price[$key].'" />
</div><!-- end .ticket -->
<div class="ticket">
<input type="text" name="_event_adress[]" value="'.$event_adress[$key].'" />
<input type="text" name="_event_price[]" value="'.$event_price[$key].'" />
</div><!-- end .ticket -->
<input type="button" class="button" id="add_ticket" value="+ Add ticket" />
</div><!-- end .event -->
<input type="button" class="button" id="add_event" value="+ Add Event" />';
}
}
//this is the save function
function wordpress_metabox_save($post_id, $post) {
// Is the user allowed to edit the post or page?
if ( !current_user_can( 'edit_post', $post->ID ))
return $post->ID;
// OK, we're authenticated: we need to find and save the data
// We'll put it into an array to make it easier to loop though.
$event_meta['_event_adress'] = $_POST['_event_adress'];
$event_meta['_event_id'] = $_POST['_event_id'];
// Add values of $event_meta as custom fields
foreach ($event_meta as $key => $value) { // Cycle through the $event_meta array!
if( $post->post_type == 'revision' ) return; // Don't store custom data twice
$value = implode('|', (array)$value); // If $value is an array, separate with |
if(get_post_meta($post->ID, $key, FALSE)) { // If the custom field already has a value
update_post_meta($post->ID, $key, $value);
} else { // If the custom field doesn't have a value
add_post_meta($post->ID, $key, $value);
}
if(!$value) delete_post_meta($post->ID, $key); // Delete if blank
}
}
The should actually be a foreach-loop but i haven't gotten that far yet that's why i wrote the same div twice to illustrate. Can someone please answer how i can save each ticket adress and price in a multidimensional array? I'm not sure if it's possible to type e.g. _event_adress[][] to store each data within a nested array? Or do i have to type the first key in?
update_post_meta
can save array as serialize value. You don't need to save each post meta value. – Rahil Wazir May 16 at 19:18$event_id
and$event_price
are coming from nowhere... Please, check the guide How to create a Minimal, Complete, and Verifiable example. . . . I also think there's no point in imploding/exploding, and if 1, 2, 3... users are insisting about that, well... maybe you should listen. Here's a full working meta box plugin with repeatable fields, that I think may help you. – brasofilo May 16 at 21:37