Support

Account

Home Forums ACF PRO How to change basic Gallery code to assign a custom size for the first photo

Solved

How to change basic Gallery code to assign a custom size for the first photo

  • Hi, i use this code to display gallery:

                            <?php 
    
                            $images = get_field('gallery');
    
                            if( $images ): ?>
                                <div class="library">
                                    <?php foreach( $images as $image ): ?>
                                        
                                            <a href="<?php echo $image['url']; ?>" class="item">
                                                 <img src="<?php echo $image['sizes']['large']; ?>" alt="<?php echo $image['alt']; ?>" />
                                            </a>
                                        
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>

    Question: How to change this code to assign a custom size for the first photo (the first photo in gallery)?

    *I have variant to solve this problem by using jQuery (by adding different classes to assign different sizes for first photo and for other photos):

    <script type="text/javascript">
    	$(".library a:first").addClass("first_photo_size");
    	$(".library a").not(":eq(0)").addClass("other_photos_size");
    </script>

    But using this jQuery code – the size of the photos varies delayed ~ 2 seconds (since it takes time to load scripts). I would like to avoid this delay, so I search solution in php (to assign different sizes for first photo and for other photos- in the initial php-code)

  • Add a counter to you loop and if it’s the first image then use a different size

    
    <?php 
      $images = get_field('gallery');
      if ($images) {
        ?>
          <div class="library">
            <?php 
              $first = true;
              foreach ($images as $image) {
                $url = $image['sizes']['large'];
                if ($first) {
                  // I made up a size here, you'll need to use a real size
                  $url = $image['sizes']['extralarge'];
                  $first = false;
                }
                ?>
                  <a href="<?php 
                    echo $url; ?>" class="item"><img src="<?php 
                    echo $url; ?>" alt="<?php echo 
                    $image['alt']; ?>" /></a>
                <?php 
              } // end foreach
            ?>
          </div>
        <?php 
      } // end if
    ?>
    
  • Thanks for the help!

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

The topic ‘How to change basic Gallery code to assign a custom size for the first photo’ is closed to new replies.