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 请教:如何用postman调用本地虚拟机区块链接上的合约?
    • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
    • ¥15 乘性高斯噪声在深度学习网络中的应用
    • ¥15 运筹学排序问题中的在线排序
    • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
    • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
    • ¥15 C++ 头文件/宏冲突问题解决
    • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
    • ¥50 安卓adb backup备份子用户应用数据失败
    • ¥20 有人能用聚类分析帮我分析一下文本内容嘛