Advanced Custom Fields is one of the most popular WordPress plugins. It is loved by developers as well as content managers as it makes editing the pages and posts very easy. It is very flexible and works easily with custom post types as well.
These are some basic examples of ACF fields retrieval using code.
How to display a simple ACF field?
There is a function in ACF that we can use to retrieve and display the field. It’s the_field($field_name). We just need to pass the field name to get the value of it and print it.
How to save a simple ACF field in a variable?
We can also save the field into a variable and then use it anywhere in the file. For that we ACF has a function get_field(‘field_name’). We just need to pass the field name just like the previous function.
How to use conditional statements on a simple ACF field?
We can use the same function get_field(‘field_name’) and use it with different conditions.
' . get_field('field_name') . '';
}
?>
The example above basically checks if get_field has any value in it. It returns false if the field is empty (value == “”) OR the value == null OR the value == false.
How to get Image field saved as URL return?
If we set the Image field as a basic URL return then it’s basically like creating a simple text variable and adding an URL to it. Though, ACF is NOT exactly doing that.
We can not dynamically set the alt since we are not setting the return value as an object. Let’s see how we can do that.
How to get Image field saved as an Object return?
The difference between the previous example and this example is that in this example, we are setting the return for the Image field as an image object. The image object will have all image attributes like alt, src, title, description and other element attributes.
By using the ID, we can also retrieve any crop size of the image and even get the name of the file!
You can read more on ACF Docs
ACF advanced basics custom image objects variables