I'm coding this website where users can create an Order (Custom Post Type) and then choose and add different Courses (Custom Post Type) to that Order. They can add and infinite number of Courses to the Order and can choose the same more than once. Then it sends an email and save the data in Wordpress
So far I can do all of that using AJAX (see below), it appends the new field with an unique ID everytime I click the button to add a Course.
I store the chosen data into input name[] arrays so I can point to it to access the meta_value (see below). But I just don't understand how to generate the meta_keys, which I could then populate with a "For each" loop. Since I don't want to limit the number of Courses they can add, I want to code something that will save every dynamically generated fields. I've pasted below my hardcoded version that works, but i'd like to do it dynamically, with a loop.
I thought about using arrays to store my meta_keys but I just don't know how that would go...
My AJAX function
$(function () {
$('#add_course').on('click', function () {
var id = $(".course_title option:selected").val();
$.ajax({
method : 'POST',
url : ajaxurl,
dataType: 'json',
data : {
action : 'my_action',
id: id
},
})
.done( function( response ) {
var title = response.title;
var price = response.price;
var time = response.time;
$("#course"+total_number_of_course+"").append('
<input type="text" name="title[]" value="'+title+'" readonly><br>
<input type="text" name="time[]" value="'+time+'" readonly>
<input type="text" name="price[]" value="'+price+'" readonly>
');
})
.fail( function() {
console.log( "error" );
})
});
});
PHP on Submit
$my_post = array(
'post_type' => 'Order',
'post_title' => $_POST['entreprise'],
'post_status' => 'publish',
'post_author' => $user_id,
'meta_input' => array(
'title1' => $_POST['title'][0],
'time1' => $_POST['time'][0],
'price1' => $_POST['price'][0],
'title2' => $_POST['title'][1],
'time2' => $_POST['time'][1],
'price2' => $_POST['price'][1]
)
);
$newpost_id = wp_insert_post($my_post);
I just want to make it work without having to hardcode it. I want to it work within a loop.