get_field()
Gets the value of the specified field or option.
This function can be used to get the value of any field from any location.
Remember that every field type returns different data types: string, integer, array, and so on.
No Hooks.
Returns
mixed. The field value.
Usage
get_field( $selector, $post_id, $format_value );
- $selector(string) (required)
- The field key or name (
nameorkey). - $post_id(integer/object)
- The post for which the specified field is saved.
Default: the current post - $format_value(true/false)
- Allows formatting to be enabled or disabled. When formatting is disabled, the value is returned as it is in the database.
Default: true
Examples
#1 Get the field value of the current post
This example shows how to get the value of the text_field field of the current post.
$value = get_field( 'text_field' );
#2 Get the field value of a specific post
This example shows how to get the value of the text_field field from post ID 123.
$value = get_field( 'text_field', 123 );
#3 Whether a field has a value
This example shows how to check whether the specified field has a value.
$value = get_field( 'text_field' );
if( $value ) {
echo $value;
}
else {
echo 'empty';
}
#4 Get one field value from different objects
This example shows the values that can be passed in $post_id to get a field from a post, user, term, or 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 );
#5 Get a field value without formatting
In this example, image is an image field that normally returns an image object. However, by passing false as the third parameter, the value is not formatted and is returned from the database as is.
Note that the second parameter is false to specify the current post.
$image = get_field( 'image', false, false );
Changelog
| Since 3.6 | Introduced. |