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 Python爬取指定微博话题下的内容,保存为txt
    • ¥15 vue2登录调用后端接口如何实现
    • ¥65 永磁型步进电机PID算法
    • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
    • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
    • ¥15 如何处理复杂数据表格的除法运算
    • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
    • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
    • ¥15 latex怎么处理论文引理引用参考文献
    • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?