我使用Wordpress高级自定义字段进行了相当基本的设置。我需要在自定义帖子中添加额外的字段,然后在帖子页面上显示它们。我有这个代码可以工作,但是当我进入一个有多个复选框选择的自定义字段时,显然该特定字段会转出单词'array',因为它是一个数组。
如何在下面创建此代码,转储常规字段的所有标签和数据以及包含数组的字段。
$fields = get_field_objects();
if( $fields )
{
echo '<div class="item-info-custom">';
echo '<dl class="item-custom">';
echo '<dt class="title"><h4>Custom Information</h4></dt>';
foreach( $fields as $field_name => $field )
{
echo '<dt class="custom-label">' . $field['label'] . ': </dt>';
echo '<dd class="custom-data">' . $field['value'] . '</dd>';
}
echo '</dl>';
echo '</div>';
}
这是我开始工作的最终代码:
<?php
$fields = get_field_objects();
if( $fields )
{
echo '<div class="item-info-custom">';
echo '<dl class="item-custom">';
echo '<dt class="title"><h4>Custom Information</h4></dt>';
foreach( $fields as $field_name => $field )
{
echo '<dt class="custom-label">' . $field['label'] . ': </dt>';
echo '<dd class="custom-data">';
if (is_array($field['value'])) {
echo implode(', ', $field['value']);
}
else {
echo $field['value'];
}
echo '</dd>';
}
echo '</dl>';
echo '</div>';
}
?>
答案 0 :(得分:1)
根据$ field ['value']中数组的组成,您可以执行以下操作之一:
如果它是一个简单的值列表,你可以将它们与implode一起粘贴。
echo '<dd class="custom-data">' . (is_array($field['value'])?implode(", ", $field['value']:$field['value']) . '</dd>';
如果数组包含的数据类似于主数组(带有标签和值键),则可以创建一个函数来呈现数组,并在遇到数组值时以递归方式调用它。
<?php
function showFields($data){
echo '<div class="item-info-custom">';
echo '<dl class="item-custom">';
echo '<dt class="title"><h4>Custom Information</h4></dt>';
foreach( $fields as $field_name => $field )
{
echo '<dt class="custom-label">' . $field['label'] . ': </dt>';
if (is_array($field['value'])){
showFields($field['value']);
}
echo '<dd class="custom-data">' . $field['value'] . '</dd>';
}
echo '</dl>';
echo '</div>';
}
$fields = get_field_objects();
if( $fields ) showFields($fields);
答案 1 :(得分:0)
您需要进行一些类型检查。您可以使用is_array()
之类的函数并执行其他逻辑。
例如:
echo '<dd class="custom-data">';
if (is_array($field['value'])) {
echo implode(', ', $field['value']);
}
else {
echo $field['value'];
}
echo '</dd>';