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">
$ck = get_post_custom_keys($post_id); //Array

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


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">
    <div class="customfield-content">
    <div class="customfield-content">

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

    $data[$k] = $cv;


  // 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>', 
         implode('</p><p>', array_map('esc_attr', $contents)));

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

  // nothing
  • Sorry, could you point out where to echo the div.customfield-box ?
    – Jen
    Commented Jan 20, 2013 at 15:55
  • @JenniferMichelle Read the comments inside the code?
    – kaiser
    Commented Jan 20, 2013 at 15:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.