Sarah McLachlane Sarah McLachlane - 1 month ago 9
jQuery Question

wordpress create meta box with multiple entries

I am trying to create a meta box for my wordpress theme where I can add Countries. Each country has a set of fields like Name, population, flag (image). I managed to create an metabox for a SINGLE country using this tutorial: http://wp.tutsplus.com/tutorials/three-practical-uses-for-custom-meta-boxes/. Any of the 3 examples work but is it possible to add more countries?

Answer

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 :)