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 CNVcaller安装后无法找到文件
    • ¥15 visual studio2022中文乱码无法解决
    • ¥15 关于华为5g模块mh5000-31接线问题
    • ¥15 keil L6007U报错
    • ¥15 webapi 发布到iis后无法访问
    • ¥15 初学者如何快速上手学习stm32?
    • ¥15 如何自动更换布娃娃图片上的衣服
    • ¥15 心理学eprime编程
    • ¥15 arduino esp8266开发
    • ¥15 stm32单片机通过485发送命令给驱动器控制电机转动,同样的代码f103可以控制电机转动,换到f407不能动了,但是用串口助手调试407显示发送的命令都是正确的,卡了好久了这是发送规则