The get_field function is a very handy function that comes from the Advanced Custom Fields plugin. It is used to get the value of a custom field of a post, user, taxonomy or theme option.
get_field Function Arguments
The function has the following signature:
<?php
function get_field(string $selector, int $post_id = false, boolean $format_value = true)
As you can see, it accepts up to 3 parameters, where the first argument selector is mandatory and the other 2 are optional:
- $selector – the field name or key
- $post_id (optional) – the post_id of which the value is saved against. Default – current post.
- $format_value (optional) – whether or not to format the value as described above. Default – true.
get_field Function Examples
Now that we know how our function works, let’s take a look at a few examples of how to use the function.
First, let’s start with a basic usage
<?php
// example 1
$value = get_field('my_custom_field');
// example 2
$value = get_field('my_custom_field', 22);
In the code sample above we see 2 examples. In example 1 we’re getting the value of the custom “my_custom_field” field for the current post. In example 2 we’re also getting the value of the custom “my_custom_field” field but for the post ID = 22.
Now let’s take a look at how we can get the value of the field and echo it if it’s not empty, otherwise echo “No value”.
<?php
$value = get_field('my_custom_field', 22);
if ($value) {
echo $value;
} else {
echo 'No value';
}
Given that the get_field function can also be used to get custom user fields, taxonomies and custom theme options, let’s take a look at how that can be done:
<?php
$post_id = false; // current post
$post_id = 1; // post ID = 1
$post_id = "user_2"; // user ID = 2
$post_id = "category_3"; // category term ID = 3
$post_id = "event_4"; // event (custom taxonomy) term ID = 4
$post_id = "option"; // options page
$post_id = "options"; // same as above
$value = get_field( 'my_custom_field', $post_id );
We can use get_field function to get an unformatted value directly from the database.
In this example, the ‘image’ field is an image field, which typically returns an image object. However, by passing false as the 3rd parameter, the value is not formatted and is returned from the database as is.
<?php
// example 1
$image = get_field('image', 22, false);
Difference Between get_field vs get_fields
In fact, these 2 functions are very similar and have a very similar function signature. The difference is that get_field returns a specific field for a given post, while the get_fields function will return an array containing all the custom field values for a specific post_id. The get_fields function is not very elegant and wastes a lot of PHP memory / SQL queries if you are not using all the values.
Wrapping Up
As you can see, the get_field function is a very handy function to get the value of a custom ACF field without having to format it manually or query it via a manual SQL query. Use it whenever