I have a post type with a relationship field.
events has a field call event_organiser which is setup as a relationship to the organiser table.
When I query the event for the organiser it returns an array of organisers( with only array element 0 present. I have set the validation on ACF to minimum 1 maximum 1 but it is still returning a single element array.
get_field('event_organiser', $post_id)
and what I want to use is
get_field('event_organiser, $post_id)['post_title']
What I have to do is
get_field('event_organiser, $post_id)[0]->post_title
I don't like having to force the [0] in there when it should only be returning an object instead of an array.
Should I just accept that this is the case?
ACF does this because the field supports multiple posts, so better to have one consistent return type. In general, it's wise to "accept that this is the case," but that doesn't mean you can't make your own customizations.
The acf/format_value
filter can be used to account for this situation if needed though (untested):
add_filter( 'acf/format_value/type=relationship', static function ( $value ) {
if ( ! is_array( $value ) ) {
return $value;
}
if ( count( $value ) > 1 ) {
return $value;
}
return array_pop( $value );
} );
This does mean that you take responsibility for any issues that are caused by these changes, like ACF changes it's return structure. Could also make debugging things more difficult, especially if you reach out to ACF support for assistance.