如何存储多个自定义元框

时间:2018-08-22 作者:topper1309

我正在尝试存储测验的多维数组,在其中动态添加问题框。但我不知道如何存储动态添加的问题框。代码如下

function wporg_add_custom_box()
{
$screens = [\'sr-quiz\'];
foreach ($screens as $screen) {
    add_meta_box(
        \'quiz_box_id\',
        \'Quiz Box\', 
        \'wporg_custom_box_html\',  
        $screen                   
    );
   }
 }
 add_action(\'add_meta_boxes\', \'wporg_add_custom_box\');

 function wporg_custom_box_html($post)
 {
 jQuery(document).ready(function(e) {
    function addQuestion(){
        var question = jQuery(\'#question-template\').clone();
        question.css("display","block").removeAttr(\'id\');
        jQuery(\'#questions\').append(question);
    }

    function renameQuestions(){
        jQuery(\'.question-box\').each(function(i,v){
            jQuery(this).find(\'.question_id\').html(i);
        });
    }

    jQuery(\'#add-question\').on(\'click\', function(e) {
        e.preventDefault();
        addQuestion();
        renameQuestions();
    });

    jQuery(document).on(\'click\',\'.del-question\', function(e)
    {
        e.preventDefault();
        jQuery(this).closest(\'.question-box\').remove();
        renameQuestions();
    });
});

<div id="questions">
<div class="question-box" id="question-template" style="display: none;">
    <h2>Question <span class="question_id"></span></h2>

    <input type="text" name="quiz[english][ques_title]" class="ques_title" placeholder="Enter question title" value="">

    <textarea name="quiz[english][ques_desc]" class="ques_desc" rows="4" placeholder="Explaination here...."></textarea>

    <a class="del-question button" href="#" data-id="1">Remove</a>
</div>
<a id="add-question" class="button" href="#">Add</a>
</div>
<?php
}
function wporg_save_postdata($post_id)
{
   $arr = $_POST[\'quiz\'];
   update_post_meta(
        $post_id,
       \'quiz_data\',
       $arr
   );
}
add_action(\'save_post\', \'wporg_save_postdata\');
我想不出解决办法,我甚至试过quiz[][quiz][english][ques_title]. 但这不起作用

1 个回复
SO网友:NiMusco

我认为这与wordpress无关。这个问题不应该是关于stackoverflow的吗?

HTML:

name="quest_title[]"
name="quest_desc[]"
PHP:

foreach($_POST[\'quest_title\'] as $key => $title)
{
    $desc = $_POST[\'quest_desc\'][$key];
    //Here do whathever you want with this $title and $desc.
}
解决方案:在名称标记的末尾使用空括号。

结束