ACF get_field() and the_field() Functions: Detailed Explanation
Key Points at a Glance
- Function Comparison: get_field() and the_field() functions both retrieve ACF field values but differ in response behavior; get_field() returns the value while the_field() prints it directly.
- Alternative Methods: Apart from the ACF API, other options include using Smart templates from the Advanced Views framework, ACF integration with page builders, or ACF shortcodes.
- Flexible Function Usage: get_field() acts as a universal entry point, enabling access to field values from any object within any available location, such as post, user, or taxonomy.
- Argument Overview: The get_field() function includes arguments such as the field selector, source ($post_id), formatting, and HTML escaping to customize value retrieval.
- Default Value Consideration: When a field is absent, the function defaults to returning NULL, potentially altering to an empty string after the first save due to default values.
- Values Escaping: Manual HTML escaping is necessary for security, achieved through functions like esc_html() or by setting the $escape_html argument of get_field() to true.
- Non-formatted Option: A lesser-known trick involves setting the $format_value argument of get_field() to false to retrieve unformatted values, useful when Return Format settings are uncertain.
Table of Contents
Intro
Advanced Custom Fields (ACF) is one of the leading meta field plugins. The get_field() and the_field() functions are some of the most important parts of the ACF API. Using these functions, you can retrieve the value of any field created with ACF, regardless of the field type. They serve as a universal entry point, facilitating access to field values.
In fact, these are the functions you're going to use most often. The ACF plugin doesn't have a separate PHP namespace, so the functions are available globally.
Important note: Both functions are available only after the plugins_loaded action, and in order to work properly, you should call them only after the acf/init hook.
1. get_field() vs. the_field() function
The get_field function and the the_field function are both provided by ACF. While they function identically in terms of retrieving field values, they differ in how they handle the response. get_field returns the value, whereas the_field prints it directly.
Thus, echo get_field() is equivalent to using the_field(). Both functions accept the same arguments, making navigation between them seamless.
Note: Our preference is to use the get_field function in all cases. The the_field function lacks utility for non-plain field types such as user or post. For instance, if used with the user data, it will print the string 'array' rather than the HTML markup of an avatar or related content as might be expected.
Below, we'll cover all the essential aspects of using the function.
2. Alternatives to the ACF get_field() and the_field() functions
Before we dive into the review of the functions, it's important to consider alternative approaches. While the ACF API, especially the get_field function, offers a straight way to retrieve ACF field values, it's essentially a wrapper around built-in WordPress features.
This means that, aside from ACF, understanding core WordPress functions and classes is crucial for managing field data. Additionally, manually writing markup and ensuring proper data escaping can be time-consuming, so exploring different methods might streamline your workflow.
a) Using the Advanced Views framework
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.
b) Utilizing integration with your page builder
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.
Here's a snapshot of the built-in features offered by some of the most popular WordPress themes and page builders for displaying ACF fields:
Theme/Builder | ACF-related feature |
---|---|
Astra | - |
Avada | Dynamic Content |
Beaver | ACF Module |
Bricks | Dynamic data |
Divi | ACF Module |
Elementor | Dynamic Tags |
GeneratePress | - |
Gutenberg | - |
Kadence | Dynamic Content |
OceanWP | - |
Visual Composer | Dynamic Content |
WPBackery | - |
While this list may seem brief, many themes come with their own page builders. Check your theme’s documentation for guidance on displaying ACF fields, or refer to the universal methods for a more flexible approach.
c) Leveraging ACF shortcodes
For retrieving values of plain fields, like text, you can employ ACF shortcodes. So if you need to insert your field value into some piece of text, such as the date, it will work well. But keep in mind that it doesn't work in more complex cases.
To retrieve values from simple fields, like text, you can use ACF shortcodes. This is especially useful when you need to insert a field value directly into content, such as displaying a date within a paragraph. However, be aware that ACF shortcodes are limited to basic use cases and may not work well for more complex scenarios.
Note: starting from ACF 6.3.0, the ACF shortcode is disabled by default for new installations. If you need to enable it, refer to the documentation on enabling the ACF shortcode.
3. Arguments of the get_field() and the_field() functions
Let's begin by reviewing the arguments for these functions. Since both share the same set of arguments, we'll cover them together:
get_field($selector, [$post_id = false], [$format_value = true], [$escape_html = false]);
- $selector (string) (Required): The field name or field key.
- $post_id (mixed) (Optional): The post ID where the value is saved. Defaults to false, which will use the current post.
- $format_value (bool) (Optional): Determines whether to apply formatting logic. Defaults to true.
- $escape_html (bool) (Optional, since 6.2.6): Returns an escaped HTML safe version of the field value. Requires $format_value to be true. Defaults to false
3.1) $selector argument
As you can see, the single required argument is the field selector, which can be either the field name or the field key. Each field has a unique ID in the format "field_uniqueid", with the second part being the unique ID response.
However, by default, the field key isn't displayed in the plugin's UI and isn't self-explanatory. We always recommend using the field name and ensuring that each field has a proper and unique name to avoid conflicts, especially if placed on the same page.
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.
3.2) Source ($post_id) argument
The second argument defines the source from which the field should be loaded. By default, it's the current object (post, page, user, taxonomy, etc.).
See the Supported sources chapter for details.
3.3) $format_value argument
The $format_value argument controls whether the meta field value should be processed by ACF before returning. By default, it's set to true, meaning ACF checks the 'Return Format' setting of the specific field and returns the corresponding value.
For example, an ACF User field stores the user ID (int) in the meta field inside the database but returns a WP_User object by default. If you change this flag, the get_field() and the_field() functions will return the raw ID (int) without any extra processing.
3.4) $escape_html argument
By default, the function's response isn't escaped, as it may contain HTML. However, in cases where HTML is not expected, we should either mark it as true or manually escape the value. Refer to the Values Escaping chapter for more details.
4. Return formats of the get_field() function
ACF offers a wide variety of field types, ranging from simple ones like Text and Number to object-related types such as Post and User, as well as group types like Gallery or Repeater. Despite the diverse value formats associated with each field type, the universal usage of the get_field() or the_field() function simplifies our workflow.
However, a couple of challenges may complicate our tasks:
a) Lack of object-related approach in get_field() response:
Ideally, get_field() would return a distinct object for each field type with predefined fields. This would allow developers to inspect object properties directly within their IDE instead of referring to documentation.
b) Return Format setting within each field:
While this setting enhances flexibility, it introduces a variety of response formats, akin to a small zoo. In addition to knowing the field type, developers must also be mindful of the Return Format setting specific to each field.
Although fields typically have default settings, caution is necessary to ensure they are not altered. This challenge can be addressed with a handy lifehack: passing true to the unformatted argument returns the 'pure' value, ensuring consistent formatting regardless of the specific field settings.
Refer to the 'Non-formatted' section of this article for further details.
Tip: You can overcome these challenges by using the Advanced Views framework. It introduces smart templates with automatic markup generation, allowing you to handle diverse field types effortlessly while maintaining control over the markup.
Below, we provide a detailed breakdown of return formats for every field type. You can bookmark this page and use it as a cheat sheet.
Note: In the table, the 'optional' multiple items support indicates the presence of an option field setting. Enabling this setting allows users to choose several items within the same field. This adjustment changes the get_field response to an array of items, regardless of the actual count, even if it's just one.
4.1) Basic group
Field type | Available return formats | Multiple items support |
---|---|---|
Text | string | no |
Textarea | string | no |
Number | integer | no |
Range | integer | no |
string | no | |
Url | string | no |
Password | string | no |
4.2) Content group
Field type | Available return formats | Multiple items support |
---|---|---|
Image | 1. array [ ID, id: int, url:string, title:string, filename: string, filesize: int, url: string, link: string, alt: string, author: int, description: string, caption: string, name: string, status: string, uploaded_to: int, date: string, modified: string, menu_order: int, mime_type: string, type: string, subtype: string, icon: string, width: int, height: int, sizes: array[ size => url ], ] 2. string (URL) 3. int (attachment id) | no |
File | the same as the image | no |
WYSIWYG Editor | string | no |
oEmbed | integer | no |
Gallery | array (see the image for the item arguments) | yes (no single at all) |
4.3) Choice group
Field type | Available return formats | Multiple items support |
---|---|---|
Select | 1. string (value) 2. string (label) 3. array [ label: string, value:string ] | optional |
Checkbox | the same as the select | yes (no single at all) |
Radio button | the same as the select | no |
Button group | the same as the select | no |
True/false | boolean | no |
4.4) Relational group
Field type | Available return formats | Multiple items support |
---|---|---|
Link | 1. array [ title: string, url: string, target: string, ] 2. string(URL) | no |
Post object | 1. WP_Post object 2. integer (id) | optional |
Page link | string | optional |
Relationship | array (see the post object for the item arguments) | yes (not single at all) |
Taxonomy | 1. WP_Term object 2. integer (id) | optional |
User | 1. array [ ID: int, user_firstname: string, user_lastname: string, nickname: string, user_nicename: string, display_name: string, user_email: string, user_url: string, user_registered: string, user_description: string, user_avatar: string, ] 2. WP_User object 3. integer (id) | optional |
4.5) Advanced group
Field type | Available return formats | Multiple items support |
---|---|---|
Google map | array [ lat: string, lng: string, zoom: int, ] | no |
Date Picker | string | no |
DateTime Picker | string | no |
Time Picker | string | no |
Color Picker | string | no |
4.6) Layout group
The layout group consists of two types of fields: visual-only and grouping. Visual-only fields, such as Tab, do not hold any value themselves. On the other hand, grouping fields do not directly affect the value but instead wrap it.
For more detailed information, check the specific guide about Group, Repeater, Flexible Content, and Clone fields.
5. Supported sources
ACF allows attaching fields to multiple different objects: posts/pages, users, taxonomies, comments, and even menus. While posts, along with pages and any custom post types, are stored in the same table, others are stored separately.
ACF automates the process and handles fetching/saving/loading values to the appropriate location. To request field values from a location different from the posts table, developers simply need to define the source ($post_id) argument with a specific prefix.
The following prefixed are supported:
- options for fields on the options page.
- user_{id} for fields on user profiles.
- category_{id} for category fields.
- {taxonomy}_{id} for fields associated with custom taxonomies.
Keep in mind that the value must remain the default false if you're retrieving fields from ACF Blocks:
$current_object_value = get_field('field_name');
$option_value = get_field('field_name', 'options');
$user_profile_value = get_field('field_name', 'user_1');
$category_value = get_field('field_name', 'category_1');
$taxonomy_value = get_field('field_name', 'genres_1');
$block_value = get_field('field_name');
Tip: While you may leave it empty, we recommend always passing a variable with the ID. This makes your code more flexible, allowing you to repurpose it easily. For example, you could turn a single template into an AJAX template that returns information based on the passed ID.
6. Default value of the get_field() function
Another important thing to note about the get_field function is its default value: NULL.
So, if a field isn't present in the object, the function will return NULL. While this might seem straightforward, it can be a bit trickier in practice. Let's consider a practical example:
- You've just added a new text field.
- You request this field for an already existing post.
- You get NULL.
This scenario seems clear. However, what happens if we open that post and press the save button? If the field has no value, ACF takes the value of the 'default value' setting of this field. When you press save, it saves the default value to the database, or an empty string if the default value isn't set.
So, since the first saving, our field will return an empty string ('') instead of NULL. All the posts made after the field was attached to the screen will also have the empty string saved in the database and returned.
It's important to keep this in mind when making WP_Query. To check if the field is empty, you should not only use 'equal to empty string' comparison but also add 'OR not exists'.
To simplify querying by Meta fields, and even Taxonomies, you can use the Pro version of the Advanced Views framework, which supports meta queries by ACF fields.
7. Values escaping
For security reasons, WordPress requires developers to escape all values coming from the database before inserting them into the markup to prevent XSS attacks. While WordPress handles this automatically for built-in functions, developers should manually escape other values using functions such as esc_html() or esc_attr().
For example, the following code is not safe:
<img src="<?php echo get_field('image_field_name'); ?>" >
This is because the value retrieved from get_field() could contain the <script> tag, which could be executed on the page. To mitigate this risk, you should either set the $escape_html argument of get_field() to true, or use the esc_attr() function like so:
<img src="<?php echo esc_attr(get_field('image_field_name')); ?>" >
To avoid constantly remembering to escape values, you can utilize a template engine like Twig or Blade, which automatically escapes all values by default. For instance, the Advanced Views framework mentioned before supports both template engines, as well as all the ACF field types out of the box.
8. Not-formatted option of the ACF get_field() function
As we described earlier, the return format of a specific field depends not only on the field type but also on the Return Format setting of that field. Let's consider the Image field as an example. Depending on the settings, the response data can be image data as an array, URL as a string, or attachment ID as an integer.
For newly added fields, you might remember the setting of the specific field. But what if you took over a project from another developer, or returned to development after a long pause? Checking the return format of every field can be time-consuming.
However, there's a not-obvious trick. It's used in the Advanced Views framework integration with ACF, and we'll share it with you. So the trick is to use the $format_value argument as false. This allows you to get the clear meta value regardless of the Return Format setting.
So when requesting an image field without formatting, you can be sure that you'll get an image ID and nothing else.
However, nothing is perfect, and for some fields, this method has a drawback. For example, for the Select field, you'll only get the chosen option without the label. In such cases, you'll need to call ACF's API to get the list of options and retrieve the label.
All of this complexity is already handled in Advanced Views, so you can use the plugin and forget about these hassles.
Summary
The ACF get_field() and the_field() functions are the most straight methods for retrieving field values. The get_field() function distinguishes itself from the the_field() function only by its response behavior: get_field returns the value, while the_field prints it.
Besides using the ACF API, there are alternative methods such as using smart templates from the Advanced Views framework, ACF integration of your page builder, or ACF shortcodes.
The get_field and the_field() functions serve as a universal entrance door, allowing you to request and print field values from any object within any available location, such as post, user, or taxonomy. This universal approach inherently determines its flexible return format: the function's return format depends on both the field type and its return format setting.
When working with the get_field function, keep in mind that the returned value isn't escaped by default. So, for cases when you don't expect HTML, don't forget to escape the value properly or pass true to the $escape_html argument of the function.
Happy ACF development!
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
- What is the purpose of the get_field() function in Advanced Custom Fields (ACF)?
The get_field() function is designed to retrieve values from fields created with ACF, offering a universal entry point for accessing field data.
- How does the get_field() function differ from the_field() function?
While both functions retrieve field values, get_field() returns the value itself, while the_field() prints it directly.
- Are there alternative methods to retrieve ACF field values besides using the get_field() function?
Yes, alternative methods include using Smart templates from the Advanced Views plugin, integrating ACF with page builders, or utilizing ACF shortcodes.
- What sources can be accessed with the get_field() function?
The get_field() function allows access to field values from various objects, including posts, users, taxonomies, comments, and menus, with the option to define the source ($post_id) argument.
- What happens if a field is absent when using the get_field() function?
If a field is absent, the function defaults to returning NULL, potentially changing to an empty string after the first save due to default values.
- Why is manual HTML escaping necessary when using the get_field() function?
Manual HTML escaping is crucial for security to prevent XSS attacks, achieved through functions like esc_html() or by setting the $escape_html argument of get_field() to true.
- Is there a way to retrieve unformatted values with the get_field() function?
Yes, setting the $format_value argument of get_field() to false allows retrieval of unformatted values, useful when Return Format settings are uncertain.
Content links (78)
72.
twig.symfony.com