Support

Account

Home Forums Add-ons Gallery Field Hide image caption if empty

Solved

Hide image caption if empty

  • Hey guys, I searched around the web and couldn’t find the answer to this.

    I have the following gallery code and I would like to hide the span portion of the code if the caption is empty. Easy breezy? 🙂

    
    <?php 
    
    $images = get_field('section_gallery');
    
    if( $images ): ?>
      <?php foreach( $images as $image ): ?>
        <div>
          <a data-fancybox="gallery" href="<?php echo $image['sizes']['large']; ?>">
            <img src="<?php echo $image['sizes']['medium']; ?>" alt="<?php echo $image['alt']; ?>">
            <span><?php echo $image['caption']; ?></span>
          </a>
        </div>
      <?php endforeach; ?>
    <?php endif; ?>
    

    Thanks!

  • Something like this should do what you need:

    
    <?php 
    
    $images = get_field('section_gallery');
    
    if( $images ): ?>
      <?php foreach( $images as $image ): ?>
        <div>
          <a data-fancybox="gallery" href="<?php echo $image['sizes']['large']; ?>">
            <img src="<?php echo $image['sizes']['medium']; ?>" alt="<?php echo $image['alt']; ?>">
            <?php if ($image['caption']) { ?><span><?php echo $image['caption']; ?></span><?php } ?>
          </a>
        </div>
      <?php endforeach; ?>
    <?php endif; ?>
    
  • Hi thanks for your answer, I don’t remember on which project I needed that in February but I’m pretty sure your solution will work for future projects.

    🙂

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

The topic ‘Hide image caption if empty’ is closed to new replies.