Mariton
Mariton

Reputation: 621

How do you do hide an empty ACF field using PHP?

I figured that I would simplify my question. This could be a PHP problem so I apologize in advanced because this may not be an ACF issue but it could be an issue of me not knowing enough PHP, I'm not sure why this isn’t working.

So I am using the ACF repeater field and I would like to hide the repeater Subfield when no data is entered in the field.

    <?php

    // check if the repeater field has rows of data

    $feature_posts = the_sub_field('feature_image_post');

    if( have_rows('repeat_field') ):

      // loop through the rows of data
        while ( have_rows('repeat_field') ) : the_row();

            // display a sub field value
              echo '<div style="float:left">';
                the_sub_field('restaurant_name');
              echo '</div>';
              echo '<div style="float:left">';
                the_sub_field('restaurant_state');
              echo '</div>';

              echo '<div style="float:left">';
                the_sub_field('restaurant_image_post');
               echo '</div>';  

                  if (empty($feature_posts)) {
                    echo '<div style="display:none">';
                    the_sub_field('feature_image_post');
                    echo '</div>'; 
                  } 

                  else {

                      the_sub_field('feature_image_post');
                  }

        endwhile;

    else :

        // no rows found

    endif;

    ?>

Upvotes: 1

Views: 1043

Answers (1)

WizardCoder
WizardCoder

Reputation: 3461

Add a conditional statement using get_sub_field to check if the field is empty. the_sub_field echos the value and get_sub_field returns the value, so it can be used in a conditional statement or stored in a variable.

if( get_sub_field('restaurant_name') != "" ) {
  echo '<div style="float:left">';
  the_sub_field('restaurant_name');
  echo '</div>';
}

Upvotes: 1

Related Questions