Custom fields PHP foreach loop

In my theme, I am using some PHP to display custom field content. It checks if the fields are empty before displaying the content, because the_meta was showing titles for empty fields.

<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>

I would like to improve this so that the ‘div.customfield-box’ does not display unless there is content. I need to echo it inside the php, but where?

The resulting html should look like:

<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>

If there is no content, it should display nothing, not even the customfield-box.

1 Answer
1

Something like this:

$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
}

Leave a Comment