dungey_140 dungey_140 - 3 months ago 26
HTML Question

WP ACF Get Attachment 'Page Link' URL on number of images in slider

I am using Advanced Custom Fields to generate a slider for my site. Each of the images (attachments) also have a custom field attached to them using the 'Page Link' option, which allows me to associate a link with each image. The code below is pulling through a link, but it is the same for each image, regardless of which one is displayed in the slider (each image should have a different link)

<section class="slideshow">
<?php
$images = get_field('slideshow');
if( $images ):
?>
<?php foreach( $images as $image ): ?>
<figure>
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />
<figcaption>
<h2><?php echo $image['caption']; ?></h2>
<h4><a href="<?php the_field('url_link'); ?>">View Case Study</a></h4>
</figcaption>
</figure>
<?php endforeach; ?>
<?php endif; ?>
</section>


I have also tried making the url_link field specific to the image as below, but this doesn't pull any information.

<h4><a href="<?php echo $image['url_link']; ?>">View Case Study</a></h4>


Many thanks in advance.

Answer

It turns out that this isn't the best use of the 'Gallery' custom field. Instead, I've turned to using the 'Repeater' field which can have sub-fields in which I can hold image, caption and link information. Code amended as follows.

<section class="slideshow">       
    <?php if( have_rows('slideshow_slides') ): ?>
        <?php while( have_rows('slideshow_slides') ): the_row(); 
            // vars
            $image = get_sub_field('image');
            $caption = get_sub_field('caption');
            $link = get_sub_field('link');
        ?>

        <figure>
            <img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt'] ?>" />
            <figcaption>
                <h2><?php echo $caption; ?></h2>
                <?php if( $link ): ?>                    
                    <h4><a href="<?php echo $link; ?>">View Case Study</a></h4>
                <?php endif; ?>
            </figcaption>
        </figure>

        <?php endwhile; ?>
    <?php endif; ?>
</section>