自定义字段PHP Foreach循环

时间:2013-01-20 作者:Jennifer Michelle

在我的主题中,我使用一些PHP来显示自定义字段内容。它在显示内容之前检查字段是否为空,因为\\u meta显示的是空字段的标题。

<div class="customfield-box">
<?php
$ck = get_post_custom_keys($post_id); //Array

        foreach ($ck as $k) {
             if (substr ($k, 0, 1) == \'_\')
             {   // skip keys starting with \'_\'
                 continue;
             }
             $cv = get_post_custom_values($k, $post_id );  //Array
                foreach ($cv as $c) {
                    if (empty ($c))
                    {   // skip empty value
                        continue;
                    }
                    $format_c = wpautop( $c, false );
                    print_r (\'\');
                    print_r (\'<h4>\' . $k . \'</h4>\');
                    print_r (\'<div class="customfield-content">\' . $format_c . \'</div>\');
                    print_r (\'\');
                }

        }
?>
</div>
我想对此进行改进,以便“div.customfield-box”不会显示,除非有内容。我需要在php中响应它,但是在哪里呢?

生成的html应如下所示:

<div class="customfield-box">
    <h4>Ingredients</h4>
    <div class="customfield-content">
        <p>Flour</p>
        <p>Salt</p>
    </div>
    <h4>Allergens</h4>
    <div class="customfield-content">
        <p>Wheat</p>
    </div>
</div>
如果没有内容,则不应显示任何内容,甚至不应显示customfield框。

1 个回复
最合适的回答,由SO网友:onetrickpony 整理而成

类似这样:

$ck = get_post_custom_keys($post_id); //Array

// drop keys starting with \'_\'
$ck = array_filter($ck, function($key){
 return strpos($key, \'_\') !== 0;
});

// store your root keys here
$data = array();

foreach($ck as $k){

  $cv = get_post_custom_values($k, $post_id );  //Array

  // drop empty values
  $cv = array_filter($cv);

  if($cv)
    $data[$k] = $cv;

}

if($data){
  // your html here; iterate over $data

  $html = \'\';

  foreach($data as $key => $contents)
    $html .= sprintf(\'<h4>%s</h4><div class="customfield-content"><p>%s</p></div>\', 
         esc_attr($key), 
         implode(\'</p><p>\', array_map(\'esc_attr\', $contents)));

  printf(\'<div class="customfield-box">%s</div>\', $html);

}else{
  // nothing
}

结束

相关推荐