wordpress创建具有多个条目的元框

时间:2014-01-09 11:50:33

标签: php jquery wordpress backend meta-boxes

我正在尝试为我的wordpress主题创建一个元框,我可以添加国家/地区。每个国家/地区都有一组字段,如姓名,人口,国旗(图片)。我使用本教程设法为SINGLE国家创建了一个元数据箱:http://wp.tutsplus.com/tutorials/three-practical-uses-for-custom-meta-boxes/。这三个例子中的任何一个都有效,但是可以添加更多国家吗?

2 个答案:

答案 0 :(得分:3)

这是对如何保存多维数组值以及如何在某种程度上解决问题的回答

你应该使用数组。

我在我的脚本中的许多实现中都这样做。让我们看看如何:

HTML / PHP优先:

<?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);
            }
        );
    }
);

然后在save_post动作挂钩函数中,您将通过$_POST得到一个看起来像这样的数组:

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

这是一般的想法。根据您的要求定制:)

答案 1 :(得分:2)

您应该考虑自定义帖子类型(http://codex.wordpress.org/Post_Types)。

在这种情况下,您可以创建一个新类型:country,其中包含帖子标题(国家/地区名称),您可以添加2个自定义字段:population(文本字段)和flag(图像字段)。

然后,您可以添加任意数量的国家/地区,就像帖子一样。