0

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>';
 }
}

2 Answers 2

0

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>';
        }
    }
}
1
  • Thank you so much! This is the solution I used and works perfectly.
    – sander
    Jun 7, 2014 at 17:27
0

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

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.