Get ACF field key programmatically by field name

心不动则不痛 提交于 2019-12-12 04:19:25

问题


I need to get the field key by field name in WordPress in the Advanced custom fields plugin (ACF).

The field is assigned to a post. I am in the loop of the post and I want to get the field key programmatically USING field name. The reason for this is because i'm creating a form where the field name 'options' will stay the same but will have different options in a select.

I am looping over a custom post type and expecting the field 'options' to be assigned to the post (each post will have unique options and so will have a unique field key so i can't just use the field key as this would be hard-coded to potentially another posts options)...

I'm in the loop of the post which should contain the custom field 'options' so I should be able to look for field key using post id and custom field name?

EDIT: I found this: https://gist.github.com/mcguffin/81509c36a4a28d9c682e

But it doesn't seem to work?


回答1:


The right way is to use acf_maybe_get_field function, just like that:

acf_maybe_get_field( 'field_name', false, false );

The arguments are: field name, post id (defaults to current post) and the most important strict which defaults to true, but we set it to false here to get field object even when it not yet exists for the post.




回答2:


I think it would be easier to tackle the problem from a different perspective.

You can filter the options in a select field for each post. See https://www.advancedcustomfields.com/resources/dynamically-populate-a-select-fields-choices/

function acf_load_option_field_choices( $field ) {
    global $post;

    $current_id = $post->ID;

    switch ( $current_id ) {

        case 101: //Post ID 101

            $field[ 'choices' ] = array(
                'ferrari' => 'Ferrari',
                'lambo'   => 'Lambo',
                'toyota'  => 'Toyota',
                'volvo'   => 'Volvo'
            );

            break;

        case 202: // Post ID 202

            $field[ 'choices' ] = array(
                'youtube'       => 'Youtube',
                'facebook'      => 'Facebook',
                'twitter'       => 'Twitter',
                'stackoverflow' => 'Stack Overflow'
            );

            break;

    }

    // return the field
    return $field;

}

add_filter( 'acf/load_field/name=options', 'acf_load_color_field_choices' );

At that point you could pull options from global options or wherever you like, they don't need to be hard coded. This means the heavy lifting is done before, and then in the loop just loop over the options like a normal ACF Field.



来源:https://stackoverflow.com/questions/42649067/get-acf-field-key-programmatically-by-field-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!