Advanced Custom Fields: Declaring what image size to use

This snippet can be placed on any of your template files to insert an image from ACF at any set image size.?You must set the return type to ‘ID’ in order for this to work. This is usually the best way to handle images with ACF as it allows much more control over the output (and?of course includes the alt tag).

Change ‘medium‘ to whatever image size you wish to use and ‘image‘ to the name of the field in ACF.

[php]
<?php
$attachment_id = get_field(‘image’);
$size = "medium";
$image = wp_get_attachment_image_src( $attachment_id, $size );
$alt_text = get_post_meta($attachment_id , ‘_wp_attachment_image_alt’, true);
?>
<img src="<?php echo $image[0]; ?>" alt="<?php echo $alt_text; ?>" />
[/php]

Using images in a “Repeater Field”?

This snippet will not work when using the repeater field. Why not? Because repeater fields are sub_fields. There’s a very simple fix for this – just use ‘get_sub_field’ instead. Here is what you should end up with:

[php]
<?php
$attachment_id = get_sub_field(‘image’);
$size = "medium";
$image = wp_get_attachment_image_src( $attachment_id, $size );
$alt_text = get_post_meta($attachment_id , ‘_wp_attachment_image_alt’, true);
?>
<img src="<?php echo $image[0]; ?>" alt="<?php echo $alt_text; ?>" />
[/php]

Leave a Reply

Your email address will not be published. Required fields are marked *