cafe_get_field()
Purpose
Returns the value of one field for a post, term, user, comment or the global options.
Syntax
cafe_get_field( string $selector, mixed $object_id = null, ?string $object_type = null, mixed $default_value = null ): mixed
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
$selector |
string | - | Field name (e.g. 'hero_title') or field key. |
$object_id |
mixed | null |
Which object. null means the current object. See the $object_id argument. |
$object_type |
string|null | null |
'post', 'term', 'user', 'comment' or 'option'. null lets CAFE work it out (numbers mean posts). |
$default_value |
mixed | null |
Returned as-is when nothing is saved. |
Return value
The saved value, formatted by the field type (a string for Text fields).
When nothing is saved: $default_value if you passed one, otherwise the field's own
Default Value setting, otherwise null. Also returns $default_value when the
field or the object cannot be found.
Example
Simplest use, inside the loop:
$title = cafe_get_field( 'hero_title' );
echo esc_html( $title );
A specific post:
$title = cafe_get_field(
'hero_title',
$post_id
);
A term, with a fallback:
$subtitle = cafe_get_field( 'subtitle', $term_id, 'term', 'Browse our products' );
Notes
- Escape on output. Values are sanitized when saved but not escaped for HTML.
- Fast by design. The first call for an object loads all its values in one
query; every other
cafe_get_field()for that object reuses them. - Values pass through the
cafe_field_valuefilters.$default_valueis returned unfiltered.