ACF:用中继器关系子字段动态填充选择字段



在这里使用了令人惊叹的解决方案,在一个中继器字段内使用文本字段填充多个选择字段。问题是我需要使用一个用户(关系)字段,而这个字段在选择框中返回任何东西。这是我使用的代码,想知道我是否需要以不同的方式调用关系字段…?

供参考:

  • 中继器字段为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');
编辑* *

发现如果我将select字段名添加到第一个$choice中,我最终得到一个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在select下拉菜单中,但是我(a)只需要名字和姓氏,(b)如果多个用户被选择,选择字段将只显示最后一个用户的usermeta在repeater字段

填充选择字段的截图

<?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的字段,可以让您选择用户

  • 您有一个名为:testrongelection的字段,它应该从中继器
  • 中选择的用户中提取。

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

最新更新