Support

Account

Home Forums General Issues Multiple images using get_field

Solving

Multiple images using get_field

  • Hello,
    I currently use custom fields to display 4 images in an archive page which the user selects when entering a new post. This code is below:

    <div class="span3">
    <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>" >
    <img src="<?php the_field('extra_image_1'); ?>" alt="<?php single_post_title(); ?>" />
    </a>
    </div>
    
    <div class="span3">
    <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>" >
    <img src="<?php the_field('extra_image_2'); ?>" alt="<?php single_post_title(); ?>" />
    </a>
    </div>
    
    <div class="span3">
    <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>" >
    <img src="<?php the_field('extra_image_3'); ?>" alt="<?php single_post_title(); ?>" />
    </a>
    </div>
    
    <div class="span3">
    <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
    <img src="<?php the_field('extra_image_4'); ?>" alt="<?php single_post_title(); ?>" />
    </a>
    </div>

    As they are photos for a photographer, I have tried to see if I can use a custom image size instead of loading the whole image (sometimes up to a meg for the full res image but the size is only 355 x 533 so I can shrink the page load down considerably – hopefully to ~50kb per image in some cases).

    I had added a new image size in functions.php and had some luck using the following:

     <?php $attachment_id = get_field('extra_image_1');
    $size = "post-portrait-featured-image"; // (thumbnail, medium, large, full or custom size)
    $image = wp_get_attachment_image_src( $attachment_id, $size );
    // url = $image[0];
    // width = $image[1];
    // height = $image[2];
    ?>
    
    <div class="span3">
    <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>" >
    <img src="<?php echo $image[0]; ?>" alt="<?php single_post_title(); ?>" />
    </a>
    </div>

    The above does exactly what I need, BUT I can’t seem to work out how to do this with four individual images as what ever I seem to do just copies the first image.

    Hopefully I’ve made sense and hopefully someone will be able to help me. I’m sure it’s starring me right in the face, just can’t work it out.

    Thanks
    D

  • Hello,

    Set the output of the image field to: “Image Array” in the ACF field set.

    Then you can view your images with custom size like this:

    
    <?php $image = get_field("image") ?>
    <img src="<?= $image["sizes"]["post-portrait-featured-image"] ?>" alt="<?= $image["alt"] ?>" />
    
  • Thank you, that works great!

    I think I was trying to over complicate things a little maybe?

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

The topic ‘Multiple images using get_field’ is closed to new replies.