skip to Main Content

We want to replace a slider with a clickable random image. So far I have half of this working using the below code that pulls one image from the ACF gallery and displays it.

What I can’t seem to find is how to then use the image’s custom link (as assigned when looaded into the WP media gallery), so that the image is also clickable (where the user loads the image and assigns the desired custom link).

Anyone have any idea how to get this to work?

Cheers!

<?php
$images = get_field('gallery', '', false);
$size = 'full';
$rand = array_rand($images ?? [null]);


if( $images ): ?>
<?php echo wp_get_attachment_image( $images[$rand], $size, "", $attr ); ?>
<?php endif; ?>

2

Answers


  1. Chosen as BEST ANSWER

    Solved! For those that want the solution, here is the code I bashed together to make an ACF Repeater powered random image with a custom link. Thanks @MindBorn for getting my brain working :)

        <?php
        $random_images = get_field('random_image_row');
        shuffle($random_images);
        $random_img_url = $random_images[0]['banner']['url'];
        $random_image_link = $random_images[0]['image_link'];
        ?>
        
        <div style="width:100%;">
    <a href="<?php echo $random_image_link; ?>" > <img src="<?php echo $random_img_url; ?>" height="400" width="1920" /></a>
        </div>
    

  2. By default in WordPress attachments like images have four editable text fields available:

    • alt-text
    • title
    • caption
    • description

    Probably not a good practice but for the record if you were to use one of these fields as the source for your image’s custom link here’s how to quickly access them:

    $images = get_field('gallery', '', false);
    $size = 'full';
    $rand = array_rand($images ?? [null]);
    $image_id = $images[$rand];
    
    $image_title = get_the_title($image_id);
    $image_alt = get_post_meta($image_id, '_wp_attachment_image_alt', TRUE);
    $image_caption = wp_get_attachment_caption($image_id);
    $image_description = get_post_field('post_content', $image_id);
    

    You haven’t exactly clarified that but I suspect that you’re actually using ACF fields group with image link custom field assigned to the attachment’s form. I’d guess its type would be url then. If this is the case, you can simply access this field’s value like this:

    $image_link = get_field('YOUR_CUSTOM_FIELD_NAME', $image_id);
    

    Then it’s just a matter of making your image clickable with the new url:

    if ($images) {
      $image_html = wp_get_attachment_image($image_id, $size);
      echo '<a href="'.$image_link.'">'.$image_html.'</a>';
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search