get_field()

Description

Returns the value of the specified field.

This is a very versatile function. You can use it to store a value, echo a value and interact with a value. Please note the type of variable returned is relative to the field type. Eg: A repeater will return a multidimensional array.

Parameters

<?php $field = get_field($field_name, $post_id, $format_value); ?>
  • $field_name: the name of the field to be retrieved. eg “page_content” (required)
  • $post_id: Specific post ID where your value was entered. Defaults to current post ID (not required). This can also be options / taxonomies / users / etc
  • $format_value: whether or not to format the value loaded from the db. Defaults to true (not required).

Usage

Get a value from the current post

$value = get_field( "text_field" );

Get a value from a specific post

$value = get_field( "text_field", 123 );

Check if value exists

$value = get_field( "text_field" );

if( $value ) {
    
    echo $value;

} else {

    echo 'empty';
    
}

Get a value from different objects

This example shows a variety of $post_id values to get a value from a post, user, term and option.

$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_field', $post_id );

Get a value without formatting

In this example, the field image is an image field which would normally return an Image object.
However, by passing false as a 3rd parameter to the get_field function, the value is never formatted and returned as is from the Database.

Please note the second parameter is set to false to target the current post

$image = get_field('image', false, false);

Related