WPLake > Learning Hub > ACF get_field() Function: Detailed Explanation

ACF get_field() Function: Detailed Explanation

Dive into ACF functions: get_field() vs. the_field(). Explore alternatives, usage, arguments, and bookmark a cheat sheet for return formats.

Key Points at a Glance

  1. 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.
  2. 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.
  3. 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.
  4. Argument Overview: The get_field() function includes arguments such as the field selector, source ($post_id), formatting, and HTML escaping to customize value retrieval.
  5. 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.
  6. 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.
  7. 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() function is one of the most important parts of the ACF API. Using this function, you can retrieve the value of any field created with ACF, regardless of the field type. It serves as a universal entry point, facilitating access to field values.

In fact, it's the function you're going to use most often. The ACF plugin doesn't have a separate PHP namespace, so the function is available globally.

It's important to note that the function is available only after the plugins_loaded action, and in order to work properly, you should call it only after the acf/init hook.

1. get_field() function 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 function usage

But before we delve into the review of the get_field function, it's worth mentioning alternative approaches. While using the ACF API, particularly the get_field function, is the most straightforward and obvious way to get ACF field values, there are other options as well.

a) Using the Advanced Views framework

The Advanced Views framework introduces Smart templates with built-in post queries and automated template generation. The plugin supports all the most renowned meta field plugins, such as ACF, MetaBox, and Pods, out of the box.

b) Utilizing integration with your page builder

ACF is a renowned plugin, and many page builders offer their own integrations with ACF. If you use one, check the documentation of your page builder to see if there is an add-on available.

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.

3. Arguments of the get_field() function

Let's start with the get_field function by reviewing its arguments:

get_field($selector, [$post_id = false], [$format_value = true], [$escape_html = false]);
  1. $selector (string) (Required): The field name or field key.
  2. $post_id (mixed) (Optional): The post ID where the value is saved. Defaults to false, which will use the current post.
  3. $format_value (bool) (Optional): Determines whether to apply formatting logic. Defaults to true.
  4. $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, 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.

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, get_field will return the raw ID (int) without any extra processing.

3.4) $escape_html argument

By default, the get_field 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() 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 typeAvailable return formatsMultiple items support
Textstringno
Textareastringno
Numberintegerno
Rangeintegerno
Emailstringno
Urlstringno
Passwordstringno

4.2) Content group

Field typeAvailable return formatsMultiple items support
Image1. 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
Filethe same as the imageno
WYSIWYG Editorstringno
oEmbedintegerno
Galleryarray (see the image for the item arguments)yes (no single at all)

4.3) Choice group

Field typeAvailable return formatsMultiple items support
Select1. string (value)
2. string (label)
3. array [ label: string, value:string ]
optional
Checkboxthe same as the selectyes (no single at all)
Radio buttonthe same as the selectno
Button groupthe same as the selectno
True/falsebooleanno

4.4) Relational group

Field typeAvailable return formatsMultiple items support
Link1. array [
title: string,
url: string,
target: string,
]
2. string(URL)
no
Post object1. WP_Post object
2. integer (id)
optional
Page linkstringoptional
Relationshiparray (see the post object for the item arguments)yes (not single at all)
Taxonomy1. WP_Term object
2. integer (id)
optional
User1. 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 typeAvailable return formatsMultiple items support
Google maparray [
lat: string,
lng: string,
zoom: int,
]
no
Date Pickerstringno
DateTime Pickerstringno
Time Pickerstringno
Color Pickerstringno

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:

  1. You've just added a new text field.
  2. You request this field for an already existing post.
  3. 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 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, which automatically escapes all values by default. For instance, the Advanced Views framework employs Twig and supports all 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 the Smart templates of the Advanced Views framework, so you can use the plugin and forget about these hassles.

Summary

The ACF get_field() function is the most direct method for retrieving field values. It 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 function serves as a universal entrance door, allowing you to request 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!

Was this article helpful?

Totally useless

Slightly helpful

Very helpful

FAQ mode

/

Learning mode

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

  6. 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.

  7. 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.

Course navigation: ACF Plugin

Content links (61)

About the Author

Maxim Akimov

Certified WordPress expert from Ukraine with over 8 years of experience. Advocate of the BEM methodology and the overall modular approach. Loves sporting activities and enjoys going to the gym and regularly plays table tennis.

0 Comments

    Leave a comment

    Reply to 

    Please be considerate when leaving a comment.

    Not shown publicly

    Got it