WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
up vote 3 down vote accepted

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
share|improve this answer
Sorry, could you point out where to echo the div.customfield-box ? – Jennifer Michelle Jan 20 '13 at 15:55
@JenniferMichelle Read the comments inside the code? – kaiser Jan 20 '13 at 15:57
Super, thanks for that edit! :) – Jennifer Michelle Jan 20 '13 at 16:05

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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