ACF:使用转发器关系子字段动态填充选择字段

时间:2016-10-28 20:10:05

标签: wordpress advanced-custom-fields

使用了很棒的解决方案here来填充转发器字段中包含文本字段的多个选择字段。问题是我需要使用用户(关系)字段而该字段在选择框中返回任何内容。这是我正在使用的代码,想知道我是否需要以不同的方式调用关系字段。?

供参考:

  • 转发器字段为co_designated_employee_representative
  • 用户字段为co_der
  • 选择要填充的字段为test_selection

这是我的代码:

function acf_load_marke_name_field_choices($field)
 {
global $post;
//Get the repeater field values
$choices = get_field('co_designated_employee_representative',$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['co_der']] = $choice['co_der'];
    }
}

// return the field
return $field;
} 

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

编辑**

发现如果我将选择字段名称添加到第一个$选项中,我最终得到了一个usermeta数组。

function select_my_field($field)
 {
global $post;
//Get the repeater field values
$choices = get_field('co_designated_employee_representative',$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['test_selection']] = $choice['co_der'];
    }
}

// return the field
return $field;
} 

add_filter('acf/load_field/name=test_selection', 'select_my_field'); 

此更改为我提供了选择下拉菜单中所有选择的usermeta,但我(a)只需要名字和姓氏;(b)如果选择了多个用户,则select字段仅显示最后一个用户的usermeta转发器领域。

Screenshot of populated select field

1 个答案:

答案 0 :(得分:0)

<?php
function select_my_field( $field ) {

    global $post;

    //Get the repeater field values
    $employees = get_field( 'co_designated_employee_representative', $post->ID );
    $choices = array();


    if ( is_array( $employees ) ) {

        // loop through the employees selected in the repeater
        foreach ( $employees as $employee ) {

            $id = $employee['co_der']['ID'];
            $name = $employee['co_der']['user_firstname'] . ' ' . $employee['co_der']['user_lastname'];

            // the user ID becomes the key and the user name is the value
            $choices[$id] = $name;
        }
    }

    // if we have new choices set the choices for our select field
    if ( $choices ) {
        $field['choices'] = $choices;
    }

    // return the field
    return $field;
}

add_filter( 'acf/load_field/name=test_selection', 'select_my_field' );

我假设以下

  • 您的转发器名称为: co_designated_employee_representative

  • 在该转发器中有一个名为: co_der 的字段,让您选择用户

  • 您有一个名为: test_selection 的字段应该从转发器中选择的用户中提取

当您在模板中检索test_selection时,它将返回用户ID。