Support

Account

Home Forums Add-ons Repeater Field 'if repeater field if empty else { …. }' doesn't work

Solving

'if repeater field if empty else { …. }' doesn't work

  • Hello,

    I’m trying to make a conditional to show a message if the field ‘downloads’ is empty. ‘downloads’ is a repeater field.

    The following code doesn’t show any message
    `<?php if( have_rows(‘downloads’) ): ?>
    <?php while( have_rows(‘downloads’) ): the_row();
    // vars
    $link = get_sub_field(‘file’);
    $name = get_sub_field(‘file_name’);
    ?>
    <?php if( $link ): ?>
    <a href=”<?php echo $link; ?>” target=”_blank”> <?php echo $name; ?>
    <?php endif; ?>
    </a>
    <?php endwhile; ?>
    <?php endif; ?>`

    and the following code should show a message if the field ‘downloads’ is empty but doesn’t work:

    `<?php if( have_rows(‘downloads’) ): ?>
    <?php while( have_rows(‘downloads’) ): the_row();
    // vars
    $link = get_sub_field(‘file’);
    $name = get_sub_field(‘file_name’);
    ?>
    <?php if( $link ): ?>
    <a href=”<?php echo $link; ?>” target=”_blank”> <?php echo $name; ?>
    <?php endif; ?>
    </a>

    <?php endwhile; else : ?>
    <p><?php _e( ‘Sorry, no files attached.’ ); ?></p>?>
    <?php endif; ?>`

    Can someone tell me what I’m doing wrong, please? Probably the problem is my basic knowledge in PHP… ?

    Thank you!

  • EDIT — Nevermind! Seems that the editor of this website replaces quotes.

    It looks like you’re using sloped quotes ‘’, and you should use regular quotationmarks like ” or “”. This type of thing occurs sometimes when you copy code from a website. Could very well be the problem!

  • The loop you’re using should work. Tested a simplified version of your code. Are you sure there are no downloads present?

    <?php if( have_rows('downloads') ): ?>
    	<?php while( have_rows('downloads') ): the_row();
    	echo 'Whoohoo! A download!';
    	?>
    	<?php endwhile; ?>
    <?php else:
    echo 'No downloads found';
    endif; ?>
  • Hello zwaarcontrast,

    Than you for your reply.

    I tried similar code and worked.

    I think the problem is when I check if the field ‘‘file’ is not empty to not show it in this case.

      
      $link = get_sub_field(‘file’);
      $name = get_sub_field(‘file_name’);
      ?>
      <?php if( $link ): ?>
      <a href=”<?php echo $link; ?>” target=”_blank”> <?php echo $name; ?>
      <?php endif; ?>
      </a>
    

    Are you sure there are no downloads present?

    Yes, I am.

    When There is a attached file look like this:
    with files

    and when there is not files look like this:
    white file

    It’s strange because I don’t have any error in my error log also the debug of WP and my server is ON so.. I don’t know exactly what is the problem.

    Thank you!

Viewing 4 posts - 1 through 4 (of 4 total)

The topic ‘'if repeater field if empty else { …. }' doesn't work’ is closed to new replies.