2013-07-11 39 views
0

我有一个相当基本的设置与Wordpress高级自定义字段。我需要将额外的字段添加到自定义帖子中,然后在帖子页面上显示它们。我有这样的代码可以工作,但是当我得到一个有多个复选框选择的自定义字段时,显然这个特定字段会抛出“数组”这个词,因为它是一个数组。倾销数组

如何在下面创建此代码,为常规字段以及其中包含数组的字段转储所有标签和数据。

$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

如果字段是数组 - 做一件事情,如果不是 - 做另一件事。 –

+0

也许通过使用is_array函数添加附加条件。如果$ field是一个数组,你添加一个额外的循环 – user

回答

0

你需要做一些类型检查。您可以使用像is_array()这样的功能并执行其他逻辑。

例如:

echo '<dd class="custom-data">'; 

if (is_array($field['value'])) { 
    echo implode(', ', $field['value']); 
} 
else { 
    echo $field['value']; 
} 

echo '</dd>'; 
+0

这是我可以工作的人。我确信其他人也是现场,我只是不知道弄清楚。这是我使用的最终代码。如果您发现任何问题,请告诉我,它似乎按我预期的方式工作。 – OcalaDesigns

+0

太好了。其他人有类似的逻辑。他们还演示了一个递归解决方案。但这可能是矫枉过正。 –

+0

谢谢贾森你的时间! – OcalaDesigns

1

根据在$场[“值”]的数组组成,你可以做下列操作之一:

如果它的值,你可以在一个简单的列表只需将它们与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); 
+0

谢谢Orangepill的时间! – OcalaDesigns