ACF Image Field: Complete Guide with 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
ACF Image field-related addons
ACF addons can be an important part of the workflow, and there are several addons especially useful for the ACF Image field:
- ACF Dropzone enhances the file upload experience in Advanced Custom Fields by enabling drag-and-drop functionality.
- ACF Image Aspect Ratio Crop focuses on setting specific aspect ratios, making sure images are cropped perfectly every time.
- Default Image for ACF automatically sets a default image for the ACF Image field when no image is uploaded, ensuring there's always a fallback visual.
- ACF Quick Edit Fields enhances the WordPress admin experience by adding Quick Edit functionality to Advanced Custom Fields. This plugin allows you to quickly view and edit ACF field values directly from the list views.
- ACF Tooltip enhances the user experience by managing lengthy instruction texts in ACF fields. Instead of cluttering the edit screen, this plugin allows you to add tooltips to field labels, keeping the interface clean and space-efficient.
- WPGraphQL for ACF allows you to expose ACF fields and field groups to GraphQL, enabling seamless querying of ACF data within your GraphQL queries.
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. ACF Image field support in Themes and Builders
ACF is one of the most popular WordPress plugins, and it's supported by many page builders right out of the box. However, most of these integrations are basic, providing limited control over layout or lacking support for advanced field types like Gallery or Repeater.
To achieve universal compatibility with any theme and page builder while gaining advanced control over your layout, consider using the Advanced Views Framework or custom code snippets as discussed in the following chapter.
Here's a snapshot of the built-in features offered by some of the most popular WordPress themes and page builders for displaying ACF Image fields:
Theme/Builder | ACF-related feature | ACF Image type support |
---|---|---|
Astra | - | no |
Avada | Dynamic Content | no (not declared) |
Beaver | ACF Module | yes |
Bricks | Dynamic data | no (not declared) |
Divi | ACF Module | yes |
Elementor | Dynamic Tags | no (not declared) |
GeneratePress | - | no |
Gutenberg | - | no |
Kadence | Dynamic Content | no (not declared) |
OceanWP | - | no |
Visual Composer | Dynamic Content | no (not declared) |
WPBackery | - | no |
While this list may seem brief, many themes come with their own page builders. Check your theme’s documentation for guidance on displaying ACF Image fields, or refer to the universal methods outlined below for a more flexible approach.
5. 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.
5.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.
5.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;
}
5.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.
6. Code snippets for the ACF Image field
ACF functions and their responses are essentially wrappers around built-in WordPress features. This means that to load and display field values, you need to be familiar not only with ACF but also with core WordPress classes and functions. Additionally, writing markup from scratch and manually escaping data can be time-consuming.
To streamline development, you can use the Advanced Views Framework. This WordPress framework offers smart templates for the front end, simplifying post queries and template creation. It generates default markup and automatically loads the escaped data into the template, allowing you to focus on the layout itself.
Unlike drag-and-drop page builders, smart templates in Advanced Views are modular and based on a template engine (Twig or Blade), providing full control over the markup and helping you avoid the pitfalls of global CSS and JavaScript files. The framework natively supports all ACF field types, along with other data sources.
Below are examples for both Advanced Views and custom code:
6.1) Loading and displaying the field value
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',
] );
6.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;
} );
6.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>';
}
6.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%);
}
6.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.6) Setting up a field-specific uploads directory
By default, all attachments are saved in the /wp-content/uploads/ folder, following the year/month structure. For instance, an image uploaded in August 2024 will be stored in /wp-content/uploads/2024/08/.
In some cases, it’s beneficial to define a specific folder for certain attachments, organizing them by topic rather than by date. While WordPress allows you to change the uploads folder using the upload_dir hook, this change applies to all uploads, including those unrelated to ACF.
Fortunately, there’s a simple solution: you can wrap the upload_dir hook within the acf/upload_prefilter hook. This code changes the custom uploads folder only for images that editors upload via a specific ACF field.
The code example below changes the uploads dir folder for the images uploaded via an ACF Image field with the image name to the /wp-content/uploads/user-images:
// https://www.advancedcustomfields.com/resources/acf-upload_prefilter/
add_filter( 'acf/upload_prefilter/name=image', function ( array $errors, array $file, array $field ): array {
// https://developer.wordpress.org/reference/hooks/upload_dir/
add_filter( 'upload_dir', function ( array $uploads ): array {
$dir = '/user-images';
$uploads['url'] = $uploads['baseurl'] . $dir;
$uploads['path'] = $uploads['basedir'] . $dir;
return $uploads;
} );
return $errors;
}, 10, 3 );
By changing the file name and target dir, you can fine-tune this snippet to your case. After that, you can add the code to your theme's functions.php.
6.7) Updating the image field programmatically
To update the Image field programmatically, you can use the ACF update_field function. Since this field stores the attachment ID, the data you pass must be an attachment ID.
add_action('acf/init', function() {
update_field('my_image_field', 123, 1); // Replace 123 with the attachment ID and 1 with the target post id
});
If you need to update the Select field on a user or term object, you must add the appropriate prefix, just as shown in the "loading" field value section.
Note: You should call the update_field function inside the acf/init action, or in any hooks that happen later.
7. 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:
7.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
}
7.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;
}
7.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;
}
7.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.
8. Related Image field filters and hooks
ACF offers a variety of filters and hooks that enable you to modify field data and behavior, extending WordPress's core hooks functionality. You can utilize the standard add_action and add_filter functions to attach custom code to these hooks.
Below are some of the most commonly used hooks along with the ACF Image field type:
8.1) acf/upload_prefilter
The acf/upload_prefilter allows you to perform custom validation on an attachment. For example, with the Image field, you can use this filter to set up a field-specific upload directory, as demonstrated earlier:
// https://www.advancedcustomfields.com/resources/acf-upload_prefilter/
add_filter( 'acf/upload_prefilter/name=image', function ( array $errors, array $file, array $field ): array {
// https://developer.wordpress.org/reference/hooks/upload_dir/
add_filter( 'upload_dir', function ( array $uploads ): array {
$dir = '/user-images';
$uploads['url'] = $uploads['baseurl'] . $dir;
$uploads['path'] = $uploads['basedir'] . $dir;
return $uploads;
} );
return $errors;
}, 10, 3 );
8.2) acf/load_field
The acf/load_field filter allows you to modify the field settings before it is displayed on the editor's screen. This filter is particularly useful for dynamically adjusting the field's configuration, such as setting default values, changing labels, or customizing available options.
add_filter('acf/load_field/name=my_image_field', function (array $field): array {
// Define allowed image sizes
$allowed_sizes = ['thumbnail', 'medium'];
// Modify the field to only allow the specified image sizes
$field['preview_size'] = 'thumbnail'; // Set a default preview size
$field['library'] = 'all'; // Allow images from the entire library (or set to 'uploadedTo' for only images attached to the current post)
// Optional: restrict the field to specific image sizes if ACF supports this in your version
if (!empty($allowed_sizes)) {
$field['mime_types'] = implode(',', $allowed_sizes);
}
return $field;
});
8.3) acf/render_field
The acf/render_field action allows you to add custom HTML before or after a field's input on the editor's screen in the WordPress admin. This can be particularly useful for adding custom-styled text, icons, styles, or additional interactive elements to enhance the field's functionality.
// todo replace field key with yours
add_action('acf/render_field/key=field_123456789abc', function (array $field):void {
// todo your custom HTML
echo '<div class="my-custom-class">Custom field-related element</div>';
});
Note: By default, the acf/render_field action is triggered after the field input has been printed. If you need to print your HTML before the input, you should set the priority number to 9 or lower in the third argument of the add_action WordPress function.
8.4) acf/validate_value
Use the acf/validate_value filter to validate the values entered into the field. You can ensure that the entered value meets specific criteria:
add_filter('acf/validate_value/name=my_image_field', function($valid, $value, array $field) {
if (true !== $valid) {
return $valid; // Skip validation if there is an existing error
}
// todo your custom validation
if (false === my_custom_value_validation($value)) {
$valid = 'Invalid value selected';
}
return $valid;
}, 10, 3);
8.5) acf/validate_save_post
The acf/validate_save_post action allows you to perform custom form validations before saving ACF fields. This is particularly useful when you need to validate one field's value based on another field's input or enforce specific rules across multiple fields.
add_action( 'acf/validate_save_post', function () {
// Get the uploaded image ID from ACF field
$image_id = $_POST['acf']['field_image_id'] ?? 0; // Replace with your Image field key
if ( ! $image_id ) {
return;
}
// Get the image metadata
$image_meta = wp_get_attachment_metadata( $image_id );
$min_width = 800; // Set minimum width requirement
$min_height = 600; // Set minimum height requirement
// Check if the image meets the required dimensions
if ( $image_meta['width'] < $min_width ||
$image_meta['height'] < $min_height ) {
// Add a validation error if the image does not meet the criteria
acf_add_validation_error( 'field_image_id', 'The uploaded image must be at least 800x600 pixels.' );
}
} );
Tip: To find the field key, navigate to the ACF field group in the WordPress admin. Click on the Screen Options button at the top right corner of the page, then check the Field Keys option. Once enabled, the field keys will be displayed next to each field name in the group.
8.6) acf/save_post
The acf/save_post action is triggered when the current item (page/product/user) is saved. You can use it to perform any additional actions, e.g. updating related data.
add_action( 'acf/save_post', function ( $post_id ) {
// Retrieve the image field value (replace with your actual image field key)
$image_id = get_field( 'project_image', $post_id ); // Field key for image
if ( ! $image_id ) {
return;
}
// Fetch the current related posts
$related_posts = get_field( 'related_posts', $image_id );
// If there are no related posts, initialize as an array
if ( ! $related_posts ) {
$related_posts = [];
}
if ( true === in_array( $post_id, $related_posts, true ) ) {
return;
}
// Add the current post ID to the related posts array
$related_posts[] = $post_id;
// Update the related posts field with the new array
update_field( 'related_posts', $related_posts, $image_id );
} );
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.