最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wordpress - Why does ACF Advanced Custom Fields return an array of posts instead of a single post when using post_id - Stack Ove

programmeradmin0浏览0评论

I have a post type with a relationship field.

events has a field call event_aniser which is setup as a relationship to the aniser table.

When I query the event for the aniser it returns an array of anisers( 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_aniser', $post_id)

and what I want to use is

get_field('event_aniser, $post_id)['post_title']

What I have to do is

get_field('event_aniser, $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?

I have a post type with a relationship field.

events has a field call event_aniser which is setup as a relationship to the aniser table.

When I query the event for the aniser it returns an array of anisers( 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_aniser', $post_id)

and what I want to use is

get_field('event_aniser, $post_id)['post_title']

What I have to do is

get_field('event_aniser, $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?

Share Improve this question asked Nov 19, 2024 at 17:31 PeterBPeterB 1092 silver badges10 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论