duandan1995 2019-04-23 17:56
浏览 56

如何存储和保存Wordpress中用户动态生成的输入字段?

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.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 树莓派与pix飞控通信
    • ¥15 自动转发微信群信息到另外一个微信群
    • ¥15 outlook无法配置成功
    • ¥30 这是哪个作者做的宝宝起名网站
    • ¥60 版本过低apk如何修改可以兼容新的安卓系统
    • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
    • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
    • ¥50 有数据,怎么用matlab求全要素生产率
    • ¥15 TI的insta-spin例程
    • ¥15 完成下列问题完成下列问题