我正在尝试为我的 WordPress 主题创建一个元框,我可以在其中添加国家/地区。每个国家/地区都有一组字段,例如名称、人口、国旗(图像)。我成功地使用本教程为单个国家/地区创建了一个元框:http://wp.tutsplus.com/tutorials/three-practical-uses-for-custom-meta-boxes/ 。这 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
操作 Hook 函数中,您将通过 $_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'
)
)
)
这是总体思路。根据您的要求进行定制:)
关于php - wordpress 创建包含多个条目的元框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21019430/