wordpress create meta box with multiple entries wordpress create meta box with multiple entries wordpress wordpress

wordpress create meta box with multiple entries


This is answering of how to save multi-dimensional array values and some how solves your problem in some level

You should use arrays.

I am doing this in many implementations in my Scripts. Lets see how:

HTML/PHP First:

<?php    $countries = get_post_meta($post->ID, 'countries' true);?><div class="EntriesContainer" data-count="<?php echo count($countries); ?>" id="itemsList">    <?php        $cnt = 0;        foreach($countries as $country)        {            ++$cnt;    ?>    <div class="newItem">        <input name="countries[<?php echo $cnt; ?>][name]" type="text" />' +        <input name="countries[<?php echo $cnt; ?>][population]" type="text" />        <input name="countries[<?php echo $cnt; ?>][flag_url]" type="text" />    </div>    <?php        }    ?></div><input type="button value="Add new Country" class="button" id="addNewItem" />

JavaScript:

jQuery(document).ready(    function($)    {        $('#addNewItem').on(            'click.myThemeOrPluginName',            function(e)            {                e.preventDefault();                var ttlItems = parseInt($('#itemsList').attr('data-count'));                ++ttlItems;                var $newItem = '<div class="newItem>' +                               '<input name="countries[' + ttlItems + '][name]" type="text" />' +                               '<input name="countries[' + ttlItems + '][population]" type="text" />' +                               '<input name="countries[' + ttlItems + '][flag_url]" type="text" />' +                               '</div>';                $('#itemsList').append($newItem);            }        );    });

Then in save_post action hooked function you will get via the $_POST an array that will look like that:

array(    'countries' => array(        [1] => array(            name => 'Greece'            population => '11000000',            flag_url => '../el_GR.png'        )        [2] => array(            name => 'Italy'            population => '????',            flag_url => '../it_IT.png'        )    ))

This is the general idea. Customize based on your requirements :)


You should consider Custom Post Types (http://codex.wordpress.org/Post_Types).

In this case, you could create a new type : country, that contains the post title (Name of country) and you could add 2 custom fields : population (text field), and flag (image field).

Then, you could add as many countries as you want, just like Posts.