Skip to content

Instantly share code, notes, and snippets.

@aibrean
Last active March 25, 2024 07:25
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save aibrean/536944c0b15b4298cc22 to your computer and use it in GitHub Desktop.
Save aibrean/536944c0b15b4298cc22 to your computer and use it in GitHub Desktop.
Demystifying the ACF image field. ACF (Advanced Custom Fields) allows users to use an ID, array, or URL for images. Once the field is set up in ACF, it’s up to you to get it to work correctly in your template/theme. This is known as the “return value” in ACF.
<?php
$image = get_field('image'); // assigns the image field to the variable of $image
if( !empty($image) ){ ?> <!-- if the $image variable isn't empty, display the following: -->
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" /> <!--displays the URL for the image variable and also the alt tag which is entered in the WordPress media library-->
<?php }; ?> <!--ends the if statement -->
<?php
$image = get_field('image'); // Creates the $image variable based on the uploaded image ID for the image field
$size = 'full'; // (thumbnail, medium, large, full or custom size) - this creates the $size variable which is based on WP image crop sizes and you can define your own in a function
if( $image ) { //if the image exists
echo wp_get_attachment_image( $image, $size ); //echo (display) the attachment based on the ID uploaded and size specified earlier.
}
?>
<?php if( get_field('image') ){ ?> <!--only shows the image field if it exists (an image was uploaded through ACF)-->
<img src="<?php the_field('image'); ?>" /> <!--displays the URL of the image if it is not an array/ID set in ACF field parameters, but a URL -->
<?php }; ?> <!-- end the IF statement -->
@DesignMeCG
Copy link

I am unable to get anything but the image-url option to work. Any other option only spits out numbers in the <img scr="111'>

@isaacaristil
Copy link

why image-id.php it's the only one who ask for size parameter ?
we ca asume the othe method take the full size by default ?

@sinisteralex
Copy link

Is there any way do this with a JSON-object that comes from an external api?

@krystyna93
Copy link

Is there a way to display the image(array) with only php and not by wrapping it in html images tags?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment