Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I wrote this function with a foreach and I'm not able to figure out how to hide the section title if there are no custom fields in $lista. Where should I place the section title?

function opening_hours_custom_fields() {

/*Define custom fields in this case with Genesis*/
$lista = genesis_get_custom_field('_happy_day', $post->ID);

/*Section title */
echo '<h3>Happy Day</h3>';
/* the rule to display items in foreach loop */
if( $lista )
 {     
foreach( $lista as $key => $value ){
    /* if value is nothing the display none */
    if( $value != '')
    {   

        echo "<li> $value </li>";
    }

}
echo '</div>';
 }
}
share|improve this question

2 Answers 2

up vote 0 down vote accepted

I would first loop over $lista and generate a new array of data that only has non-empty values. Now you can check $values to ensure there is data and output your title:

function opening_hours_custom_fields() {
    global $post;

    if ( $lista = genesis_get_custom_field( '_happy_day', $post->ID ) ) {
        $values = array();
        foreach ( $lista as $value ) {
            if ( $value != '' )
                $values[] = $value;
        }

        if ( $values ) {
            echo '<h3>Happy Day</h3>';
            echo '<ul>';
            foreach ( $values as $value )
                echo "<li>$value</li>";
            echo '</ul>';
        }
    }
}
share|improve this answer
    
Thank you so much! This is the solution I used and works perfectly. –  sander Jun 7 at 17:27

As long as the loop only will be executed if there are any custom fields you could just move the title just before the foreach loop:

/* the rule to display items in foreach loop */
if( $lista )
{  
  /*Section title */
  echo '<h3>Happy Day</h3>';

  foreach( $lista as $key => $value ){
share|improve this answer

Your Answer

 
discard

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.