How to get Advanced Custom Field choice value from

2019-07-18 08:52发布

问题:

I have created two custom fields using Advanced Custom Field plugin. I want it to behave like when I insert value in one text field, it should be filled in the another field which is a choice field.

This image is an example where I am inserting Name value and slug value. I want it to return this.

回答1:

To auto populate select fields in ACF, you can use the load_field function - see more here: http://www.advancedcustomfields.com/resources/acfload_field/

So, let's say your select field name was marke_name, you could add the following to your functions.php file and this will populate the field every time for you

function acf_load_marke_name_field_choices($field)
{
    global $post;
    //Get the repeater field values
    $choices = get_field('repeater_field_name',$post->ID);
    // loop through array and add to field 'choices'
    if (is_array($choices)) {
        foreach ($choices as $choice) {
            //Set the select values
            $field['choices'][$choice['slug']] = $choice['name'];
        }
    }

    // return the field
    return $field;
}

add_filter('acf/load_field/name=marke_name', 'acf_load_marke_name_field_choices');


回答2:

Create a javascript file with the following (replace both ids with the id of the field, if I'm right it should start with acf-field-)

(function($) {
    $('#id_of_input_with_value').on('blur', function(){
        $('#id_of_input_which_should_get_input_value').val($(this).val());
    });
})(jQuery);

In your functions.php make sure the js file is loaded in the admin area (in this example the link-acf-fields.js file is inside a js folder within my theme):

function my_custom_admin_scripts() {
    wp_register_script('link-acf-fields', get_template_directory_uri() . '/js/link-acf-fields.js', 'jquery', false, true );
    wp_enqueue_script('link-acf-fields');
}
add_action( 'admin_enqueue_scripts', 'my_custom_admin_scripts' );