WP Advanced Custom Fields: link images to media file

In my page templates I’m including an image using the image field, like this:

<?php
    $image = get_field('img');
    echo '<img src="' . $image['sizes']['large'] . '" alt="' . $image['alt'] . '" />';
?>

I’d like to automatically wrap those images with a link to the full-size media file, just like when inserting images using the default WP WYSIWYG editor and selecting “Link To: Media File”.

Read More

So the html output would be something like:

<a href="../link-to-media-file.jpg">
    <img src="../media-file.jpg" alt="alt-text" >
</a>

This is probably really simple, and maybe I’m overlooking the obvious, but somehow I’m not coming up with a solution.

Related posts

Leave a Reply

2 comments

  1. According to the documentation try

    <?php 
    $image = get_field( 'image' );
    if( ! empty( $image ) ) { 
        // vars
        $url    = $image['url'];
        $title  = $image['title'];
        $alt    = $image['alt'];
    
        $size   = 'large'; // (thumbnail, medium, large, full or custom size)
        $pic    = $image['sizes'][ $size ];
        $width  = $image['sizes'][ $size . '-width' ];
        $height = $image['sizes'][ $size . '-height' ];
    ?>
        <a href="<?php echo $url; ?>" title="<?php echo $title; ?>">
            <img src="<?php echo $pic; ?>" alt="<?php echo $alt; ?>" width="<?php echo $width; ?>" height="<?php echo $height; ?>" />
        </a>
    <?php } ?>
    
  2. As opposed to Volker’s answer, try this:

    <?php $img = get_field('image'); ?>
    <img src="<?php echo $img['sizes']['$size']; // either large, small, medium or a custom size of your own choice! :) ?>" />
    

    It’s a little tidier and easier to read through, and it outputs the exact same thing.

    Check the documentation for more info.