ACF Image Field Guide: Essentials and Code Snippets
Key Points at a Glance
- Validation settings: Editors can define minimum and maximum dimensions, file size, and restrict file types to ensure only specific images are uploaded.
- Duplicates: WordPress does not check for duplicate images during upload, so managing file names and checking the media library is essential to avoid redundant storage.
- Supported Locations: The ACF Image field can be applied to various locations like posts, pages, user profiles, options pages, and even custom Gutenberg blocks.
- Image Lightbox: Enhances image viewing by allowing users to view images in a full-screen mode using either a plugin or JavaScript library.
- Image as Background: The ACF Image field can also be used to set an image as a background for an element, providing more design flexibility.
- Custom Queries: To find items based on specific image fields, different query methods like WP_Query, WP_Term_Query, or WP_User_Query are used, depending on where the image data is stored.
Table of Contents
ACF Image is a field type in the Advanced Custom Fields plugin that belongs to the Content group. This field enables editors (or users) to upload or select images directly from the WordPress media library.
ACF Image field UI
Image fields in other meta-field plugins
If you're looking for ACF alternatives, the ACF Image field is similar to the Image field in the Meta Box plugin and the Image field in the Pods plugin. Read our comparison of the best meta field plugins to learn about the differences between vendors.
1. ACF Image field essentials
1.1) Field settings
General settings
This tab includes settings for handling and returning the data.
- Return Format
This setting controls the format in which the field’s value is returned when using the get_field() function in your theme or plugin. Options:
Array: Returns an array containing all the file data, including URL, title, description, and more.
URL: Returns just the URL of the file.
ID: Returns the attachment ID of the file. - Library:
This setting allows you to control which files are available for selection within the media library. Options:
All: The editor can select any file from the media library.
Uploaded to Post: Restricts the selection to files that editors uploaded specifically to the current post or page.
Validation settings
This tab includes settings that define which files users can upload.
- Minimum (Dimensions, Size)
Defines the minimum allowed dimensions (for images) or size (for any file type). Options:
Minimum Dimensions: Set a minimum width and height for image files.
Minimum Size: Set a minimum file size (e.g., 1 MB). - Maximum (Dimensions, Size)
Defines the maximum allowed dimensions (for images) or size (for any file type). Options:
Maximum Dimensions: Set a maximum width and height for image files.
Maximum Size: Set a maximum file size (e.g., 5 MB). - Allowed File Types
Restricts the types of files you can upload, so you can specify allowed file types by their extension, such as .jpg, .png, .pdf, .docx, etc.
Presentation settings
This tab focuses on how the WordPress admin area displays the field and its contents.
- Preview Size:
Controls the size of the image preview that appears in the field when you select an image file.
Default options:
Thumbnail: Shows a small, thumbnail-sized preview of the image.
Medium: Displays a medium-sized preview.
Large: Provides a larger preview of the image.
Full Size: Displays the image at its full size, which may be scaled down based on the display area.
1.2) Storage format and supported field locations
The ACF Image field saves the selected image's ID in the database, which is a reference to the image stored in the WordPress media library. In WordPress, attachments, including images, are treated as a post type, similar to pages, products, and other content types.
This means that when you upload a file to the media library, WordPress stores it as a post in the wp_posts table. The ID you see for an image in the ACF Image field is actually the post ID of the corresponding attachment.
Whether the image is used in posts, pages, custom post types, or within ACF fields, WordPress utilizes this attachment ID to reference the image's metadata, such as its URL, title, alt text, and other properties.
Note: the post in the wp_posts table doesn't store the actual image file. Instead, it stores the image's metadata, such as its URL, title, alt text, and other properties. WordPress stores the physical image file itself in the /wp-content/uploads folder of your installation.
Supported field locations
You can use the ACF Image field in various locations, and it consistently stores the image ID regardless of where you apply the field:
- Post Objects (Post, Page, Media Attachment, CPT Item, WooCommerce Product):
All content types, including pages, media attachments, and custom post types, are stored in the wp_posts table. The image ID from the ACF Image field is stored in the wp_postmeta table, associated with the relevant post or custom post type item. - Options Page:
The Image field can be used on an ACF Options Page, storing the image ID in the wp_options table. This makes the image accessible as a global site-wide setting, useful for elements like a site logo or default image. - User Profiles:
When the Image field is added to user profiles, the selected image ID is stored in the wp_usermeta table, linked to the corresponding user. This is particularly useful for user avatars or profile pictures. - Terms (e.g., Post Categories):
The Image field can be attached to terms, such as post categories, tags, or custom taxonomies. In this case, the image ID is stored in the wp_termmeta table, connected to the specific term. - ACF Gutenberg Block:
The Image field can be added to custom ACF blocks. When used within an ACF Block, the image ID is stored within the post_content as part of the block's JSON data structure in the wp_posts table, making it part of the block's content.
1.3) Return Value Formats
The Return Value setting determines how the image is returned when using the get_field() function.
Here’s a breakdown of the options:
- Image Array:
Returns an array containing the image URL, alt text, caption, description, and dimensions. This is the most versatile option if you need more than just the image URL. See the code snippet below for the full list of array keys. - Image URL:
Returns the URL of the selected image, which is useful for simple image outputs in your templates. - Image ID:
Returns the ID of the image in the WordPress media library, which can be useful when you need to perform additional queries or retrieve specific image sizes.
Array keys:
$file = [
'ID' => 123, // int: The attachment ID
'url' => 'https://example.com/image.png', // string: The image's URL
'title' => 'Sample Image', // string: The image's title
'filename' => 'image.png', // string: The image's filename
'filesize' => 102400, // int: The image's size in bytes
'link' => 'https://example.com/image.png', // string: The image's permalink
'alt' => 'An example image', // string: Alternative text for the image
'author' => 1, // int: ID of the image's author
'description' => 'This is a sample image.', // string: Image description
'caption' => 'Image caption', // string: Image caption
'name' => 'image', // string: The name (slug) of the image
'status' => 'inherit', // string: Post status (usually 'inherit' for attachments)
'uploaded_to' => 456, // int: ID of the post the image was uploaded to
'date' => '2024-08-26 12:34:56', // string: The upload date
'modified' => '2024-08-26 12:35:56', // string: The date the image was last modified
'menu_order' => 0, // int: Order within a menu
'mime_type' => 'image/png', // string: MIME type of the image
'type' => 'image', // string: General type of the image
'subtype' => 'png', // string: Specific subtype of the image
'icon' => 'https://example.com/icon.png', // string: URL to the icon representing the image
'width' => 800, // int: Width of the image
'height' => 600, // int: Height of the image
'sizes' => [ // array: Different sizes of the image
'thumbnail' => 'https://example.com/image-thumbnail.png',
'medium' => 'https://example.com/image-medium.png',
'large' => 'https://example.com/image-large.png',
],
];
1.4) Image sizes
When you upload a new image in WordPress via the Media Library, WordPress automatically generates several thumbnail versions of the image, each with different dimensions.
These thumbnails are scaled versions of the original image, preserving the aspect ratio to ensure that your images display correctly across various devices without compromising performance. For instance, loading a 2000x3000px image on a 300px-wide mobile screen is unnecessary and could slow down page loading times.
By default, WordPress generates the following image sizes in addition to the original:
- Thumbnail: 150px square
- Medium: Maximum width and height of 300px
- Medium_large: Maximum width and height of 768px
- Large: Maximum width and height of 1024px
You can fine-tune the default sizes in the Site Settings->Media page, as well as add more sizes (programmatically).
Even though these are different versions, they all stem from the same original image. In WordPress, each image attachment has a single image ID, and the sizes are accessed through string arguments like 'thumbnail,' 'medium,' 'medium_large,' and 'large'.
When you insert an image into a post or page using the Gutenberg editor, WordPress automatically creates an img tag with a srcset attribute. The srcset attribute helps the browser decide which image size to load based on the screen size, ensuring optimal performance and quality.
You can read more about image sizes in WordPress in this wordpress.com article.
1.5) Alternative field types
While the ACF Image field is designed for selecting and storing a single image, there are alternative field types within ACF:
- Gallery
The ACF Gallery field is ideal when you need to store a collection of images rather than just one. It allows users to select and manage multiple images within a single field. This is especially useful when you're uncertain about the exact number of images required, as the Gallery field is flexible enough to accommodate both a single image and an entire set. - File
The ACF File field should be used when dealing with non-graphical file types, such as PDFs, Word documents, or any other file types that aren't images. Although these files are also handled as attachments in WordPress and stored in the wp_posts table like images, they don't have a preview in the media library.
2. Use cases of the ACF Image field
The ACF Image field is versatile and you can use it in various scenarios:
- Extra Post or Page Thumbnail
WordPress's Post Thumbnails feature, commonly referred to as Featured Images, allows you to assign a custom image to posts, pages, or custom post types. Since the Featured Image is a single image, you can enhance this functionality by using the ACF Image field. - Custom logo or header image
Use the Image field on an ACF Options Page to manage site-wide assets like a logo or header image, ensuring consistency across your site. - User avatars
Add the Image field to user profiles to allow custom avatars or profile images, enhancing the user experience on sites with user-generated content. - Category thumbnails
Use the Image field to assign custom images to categories or tags, providing a visual representation for taxonomy terms. - Custom map marker icon
ACF provides specialized field types such as ACF Google Maps and OpenStreetMap (OSM) for integrating maps into your site. If you want to give editors the ability to define custom marker icons dynamically, the ACF Image field is an excellent choice.
3. Duplicates and ACF Image field
When you upload a new image to WordPress, it creates a new attachment entry in your Media Library. WordPress does not automatically check if the image you're uploading already exists, so even if you're uploading a duplicate, a new attachment will be created.
To prevent accumulating duplicate images, it's important to:
- Give images clear names: Use descriptive filenames to avoid confusion.
- Search the Media Library first: Check if the image already exists before uploading it again.
Failing to do this can lead to increased storage usage on your web hosting account and potential management issues.
Additionally, removing an image from an ACF Image field does not delete the image from your WordPress installation. The image will remain in your Media Library even if it's no longer assigned to any posts or pages.
4. How to add Lightbox to the ACF Image field
Displaying images with the ACF Image field is straightforward, but you might face situations where the image width is constrained, and users may need a closer look. To address this, you can implement either a lightbox or a zoom effect.
A lightbox is ideal for providing a full-screen view of images, offering a more detailed examination. On the other hand, a zoom effect allows for partial enlargement upon clicking, which is useful for enhancing the visibility of specific areas of an image without disrupting the layout, as you can see in our articles.
Below, we review the lightbox solution. If you prefer a scale effect instead, refer to the scale example in the 'Code Snippets' chapter.
4.1) Image LightBox using the Pro edition of the Advanced Views Framework
The AVF: Pro Edition allows you to manage front-end assets effortlessly and comes with pre-configured libraries for sliders, masonry layouts, and image galleries, which you can apply to the related meta fields.
The framework handles including the libraries and provides the default markup and instance configuration, while you can fine-tune everything according to your needs. To create and connect the LightBox instance use the following steps:
- Open the target View
Access the View where your ACF Image field is used. - Enable the Lightbox option
In the field settings, find and enable the lightbox option. This will automatically enqueue the required library and add the basic JavaScript setup to the JS code field. - Customize the setup
You can customize the lightbox settings in the JS code field according to your specific needs. - Save the View
For this example, we've used the following instance JS settings:
var image = this.querySelector('.acf-view__image');
if (image) {
/* https://www.lightgalleryjs.com/docs/settings/#lightgallery-core */
new lightGallery(image, {
selector: 'this',
closeOnTap: true,
counter: false,
download: false,
allowMediaOverlap: false,
enableDrag: false,
});
}
For details, refer to the Lightbox setup guide in AVF Image Docs.
4.2) Image LightBox using a third-party plugin
Alternatively, you can use the Simple Lightbox plugin:
- Install the Plugin
Download and install the Simple Lightbox plugin from the WordPress repository. - Call the Plugin Function
After activating the plugin, call the Simple Lightbox function on your image markup to enable the lightbox effect as shown in the plugin Docs:
$image = get_field( 'your_image_field' ); // from the current post
if ( $image ) {
// arguments: id, size, icon, attributes
$image = wp_get_attachment_image( $image['ID'], 'medium', false, [
'class' => 'my-image',
] );
echo true === function_exists( 'slb_activate' ) ?
slb_activate( $image ) :
$image;
}
4.3) Image LightBox using a specific library
The exact code will depend on the chosen lightbox JS library, but the common steps are:
- Choose a JavaScript library
Select a lightbox library like LightGallery. Download the script from its official source. - Add the downloaded script to your theme's directory and enqueue it.
- Add initialization code
Include the necessary JavaScript code in your theme’s JS file to initialize the lightbox.
5. Code snippets for the ACF Image field
ACF provides hooks and functions for customizing and displaying field values. Direct API usage offers flexibility but requires familiarity with ACF and the specific return formats configured in the field settings.
To streamline development, you can use the Advanced Views Framework, which simplifies query and display tasks while allowing full control over markup. It supports all ACF field types out-of-the-box, along with other data vendors.
Below are examples for both Advanced Views and ACF functions:
5.1) Displaying the chosen image
Using Advanced Views Framework
- Navigate to the Views section and create a new View.
- Select the Image field in the Fields tab.
- Save the View; a template will be automatically generated. You can copy and modify this template as needed.
- To integrate it into your page, paste the generated shortcode or use the Custom Gutenberg block option.
Loading from different locations: To load a field from different locations (e.g., user profile), use the object-id shortcode argument.
Using ACF get_field() Function
The get_field function response will differ based on the chosen return format:
1. Array return format (default)
$image = get_field( 'your_image_field' ); // from the current post
$image = get_field( 'your_image_field', 10 ); // from a specific post by ID
$image = get_field( 'your_image_field', 'option' ); // from the options page
$image = get_field( 'your_image_field', 'user_1' ); // from the user by ID
$image = get_field( 'your_image_field', 'category_2' ); // from the category term with ID 2
$image = get_field( 'your_image_field', 'genre_3' ); // from the custom genre term with ID 3
// prefer the function over manual markup creation, as WordPress makes srcset and sizes attributes there for you.
// arguments: id, size, icon, attributes
echo wp_get_attachment_image( $image['ID'], 'medium', false, [
'class' => 'my-image',
] );
2. Url return format
Try to avoid this return format, as doesn't allow us to create responsive images.
$image = get_field( 'your_image_field' ); // from the current post
$image = get_field( 'your_image_field', 10 ); // from a specific post by ID
$image = get_field( 'your_image_field', 'option' ); // from the options page
$image = get_field( 'your_image_field', 'user_1' ); // from the user by ID
$image = get_field( 'your_image_field', 'category_2' ); // from the category term with ID 2
$image = get_field( 'your_image_field', 'genre_3' ); // from the custom genre term with ID 3
// we can't use wp_get_attachment_image as image ID is not available. Try to avoid this return format.
printf('<img src="%s">', $image);
3. ID return format
$image = get_field( 'your_image_field' ); // from the current post
$image = get_field( 'your_image_field', 10 ); // from a specific post by ID
$image = get_field( 'your_image_field', 'option' ); // from the options page
$image = get_field( 'your_image_field', 'user_1' ); // from the user by ID
$image = get_field( 'your_image_field', 'category_2' ); // from the category term with ID 2
$image = get_field( 'your_image_field', 'genre_3' ); // from the custom genre term with ID 3
// prefer the function over manual markup creation, as WordPress makes srcset and sizes attributes there for you.
// arguments: id, size, icon, attributes
echo wp_get_attachment_image( $image, 'medium', false, [
'class' => 'my-image',
] );
5.2) Allowing SVG uploading
By default, WordPress restricts SVG file uploads due to security concerns. SVG files, being XML-based, can potentially contain malicious code that might compromise your site.
However, if you need to enable SVG uploads for specific user roles, such as editors and administrators, you can do so by white-listing the SVG extension.
There are a couple of options:
- Use the Safe SVG Plugin
This free plugin not only allows SVG uploads but also sanitizes the files to remove any potentially harmful code. It also enables a preview of SVG files in the Media Library. - Add a white-listing code
If you prefer a straightforward method without additional plugins, you can use the following code snippet to whitelist SVG uploads for editors and admins:
add_filter( 'upload_mimes', function ( array $mimes ): array {
$roles = wp_get_current_user()->roles;
if ( false === in_array( 'administrator', $roles, true ) &&
false === in_array( 'editor', $roles, true ) ) {
return $mimes;
}
$mimes['svg'] = 'image/svg+xml'; // Allow SVG uploads
return $mimes;
} );
5.3) Wrapping an image in a link
Turning an image into a clickable link can be very useful in various cases. You can link the image to a specific hardcoded URL or use dynamic links defined by editors:
Using Advanced Views Framework
- Create a View:
Go to the Views section in the Advanced Views Framework and create a new View. - Add fields:
In the Fields tab, add the target link field and the image field you want to use. - Save the View:
Save the View to generate the default template. - Modify template:
Copy the default template and paste it into a custom template field. Modify the template to wrap the image with a link as mentioned in the framework Docs:
<a href="{{ link.url }}" target="{{ link.target }}">
<img src="{{ image.value }}" width="{{ image.width }}" height="{{ image.height }}" alt="{{ image.alt }}" decoding="{{ image.decoding }}" loading="{{ image.loading }}" srcset="{{ image.srcset }}" sizes="{{ image.sizes }}">
</a>
Using get_field() function
$image = get_field( 'your_image_field' ); // from the current post
$link = get_field( 'your_link_field' ); // from the current post
if ( $image && $link ) {
printf( '<a href="%s">', esc_url( $link['url'] ) );
echo wp_get_attachment_image( $image, 'full' );
echo '</a>';
}
5.4) Setting a scale-on-click effect
As an alternative to using a lightbox for image viewing, you can implement a "scale" effect that enlarges the image on click without affecting the surrounding layout. This approach offers a simple way to view larger versions of images directly within blog posts or other content areas.
The general principle will be similar whether you're using the Advanced Views Framework or your theme's PHP code. With AVF, you won’t need to worry about enqueueing CSS and JS. See the AVF Image page in the documentation for ready-to-paste code for your View.
If you prefer to use the get_field function and include the CSS/JS in your theme assets, we’ve provided code snippets below:
HTML Code
To implement the scale effect, you need to add a specific class to your image. Here’s an example of how you can do this using PHP and ACF:
$image = get_field( 'your_image_field' ); // from the current post
if ( $image ) {
echo wp_get_attachment_image( $image, 'full', false, [
'class' => 'image',
] );
}
JavaScript Code
Add the following JavaScript code to your theme's JavaScript file to enable the scale effect on click:
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('.image').forEach((image) => {
image.addEventListener('click', () => {
image.classList.toggle('image--zoomed');
});
});
});
CSS Code
Add the following CSS to your theme’s style.css to handle the visual scaling of the image:
.image {
z-index: 999;
transition: all .5s ease;
cursor: zoom-in;
}
.image--zoomed {
cursor: zoom-out;
transform: scale(130%);
}
5.5) Using an image as a background image
Using an image as a background is a common design technique, especially when you want to overlay text or other content on top of the image. Instead of directly displaying an image using the <img> tag, you can set it as the background for a specific element.
This requires adding an inline style to the target element and setting the image URL as the value for the background-image property:
Using Advanced Views Framework:
Amend the target View's template to add the inline style:
<div class='acf-view__image' style='background-image: url({{ image.value }});'>
{# block content #}
</div>
And don't forget to add the following CSS into the CSS field of your View as shown in the AVF Image Docs:
#view__image {
background-size: cover;
background-position: center;
}
Using get_field() function
$image = get_field( 'my_image' );
if ( $image ) {
// We only need the image URL, so we use wp_get_attachment_image_url instead of wp_get_attachment_image.
$image_url = wp_get_attachment_image_url( $image['ID'], 'full' );
printf(
'<div style="background-size: cover; background-position: center; background-image: url(%s);">
<p>Some label</p>
</div>',
esc_url( $image_url )
);
}
Another approach is to use an <img> tag within the target element and position it absolutely. This method allows for more control over the image, such as adding effects or transitions.
6. Querying by the ACF Image field
When working with the ACF Image field, you might need to find items with a specific image. Unlike displaying the image, querying items by these values can be more complex due to varying storage locations for ACF fields.
Here’s how to handle queries depending on where the Image field values are stored:
6.1) By postmeta (Post, Page, Any CPT)
Using Advanced Views Framework:
If you're using the AVF: Pro edition, querying by ACF Image field values is straightforward with Meta Queries. You need to create a Card, choose the target Image field in the Meta Fields tab, and define the desired value. It can be a static id or pointer to another field. Then the framework will take care of the rest.
Using WP_Query
For custom queries, you can use the built-in WP_Query class:
$args = array(
'post_type' => 'post', // or your CPT
'post_status' => 'publish',
'posts_per_page' => -1, // means unlimited
'meta_query' => array(
array(
'key' => 'your_image_field',
'value' => 10, // target image id
)
)
);
$query = new WP_Query($args);
foreach($query->get_posts() as $post){
// todo WP_Post $post
}
6.2) By termmeta (Terms)
Here we need to employ the WP_Term_Query class:
$args = array(
'taxonomy' => 'category', // Replace with your taxonomy
'meta_query' => array(
array(
'key' => 'your_image_field',
'value' => 10, // target image id
)
)
);
$term_query = new WP_Term_Query($args);
foreach ($term_query->get_terms() as $term) {
// Process each WP_Term object
// Example: echo $term->name;
}
6.3) By usermeta (user profile)
In this case, we need to use the WP_User_Query class:
$args = array(
'meta_key' => 'your_image_field',
'meta_value' => 10, // target image id
);
$user_query = new WP_User_Query($args);
foreach ($user_query->get_results() as $user) {
// Process each WP_User object
// Example: echo $user->user_login;
}
6.4) Inside ACF Blocks
ACF Blocks save their data as JSON in the post_content. This data cannot be queried directly. However, if you enable the "Save in Meta" feature for ACF Blocks, the field values are also saved in post meta, allowing you to query them similarly to other postmeta fields.
Thank you for reading! to our monthly newsletter to stay updated on the latest WordPress news and useful tips.
Stuck with development or facing an issue?
WPLake offers affordable on-demand website development and design.
No matter the size of your project - contact us now, and we'll get it done for you!
Frequently Asked Questions Test Your Knowledge
FAQ mode
/
Learning mode
- Can I restrict uploading images in the ACF Image field by a specific ratio?
While ACF itself does not natively support aspect ratio restrictions directly within its default validation settings, you can enforce such constraints using a free ACF Image Aspect Ratio addon. This addon introduces a new field type with an aspect ratio limit setting. It forces editors to crop or resize the image to meet the specified aspect ratio or pixel size after uploading.
- Can I define a default Image in the ACF Image field?
ACF does not offer a built-in 'default' image setting for the Image field type. However, you can easily introduce a 'default' Image field to your ACF Options page and use it in your code as a fallback whenever the image field is empty.
- Can I use an ACF Image as a map marker for the ACF Map field?
Yes, absolutely. By default, the ACF Map field displays a standard map marker. However, you can customize this by adding a custom image field specifically for the marker. This allows editors to dynamically define the marker image for each map point. To learn more about implementing this, check out our ACF Map Field article.