获取高级自定义字段的选择框值

时间:2014-04-28 16:27:05

标签: wordpress advanced-custom-fields

我正在使用字段的转发字段类型。父字段名称为'map_details',子字段名称为'name_of_county',这是一个选择下拉列表。

现在我想在前端显示该选择框的所有值。我的代码是

$field_key = "field_535befe551ba5"; //field key of parent
$field = get_field_object($field_key); 

if( $field )
{
    echo '<select name="' . $field['key'] . '">';
        foreach( $field['choices'] as $k => $v )
        {
            echo '<option value="' . $k . '">' . $v . '</option>';
        }
    echo '</select>';
}

它没有工作,因为我给了父字段的字段键而不是子字段,它基本上是一个选择框。我也找不到子字段的字段键。

如何在前端显示带有值和键的子字段下拉框。

1 个答案:

答案 0 :(得分:1)

我最近找到了在前端输出值/键的方法: 在这些情况下,我总是print_r父数组(在&#39; pre&#39;标记之间)以了解正在发生的事情,相信我......这有帮助。 与在转发器中一样,选择字段(sub_field)在数组中更深一些,因此:

$field_key = "field_535befe551ba5"; //field key of parent
$field = get_field_object($field_key); 

if( $field ) {

    // As explained, it's better to first take a look to
    // the array's structure. Uncomment the next 3 lines
    // to print it in a pretty way

    // echo '<pre>';
    // print_r ($field);
    // echo '</pre>';

    foreach ($field['sub_fields'] as $the_subfield) {
        $the_subfield_name = $the_subfield['name'];

        // in case that you have more than one subfield in the repeater
        // we need to check that we are in the desired subfield:
        if ($the_subfield_name == 'name_of_the_subfield') {
        //in your case: 'name_of_country'

            // now that we are sure that we are inside the desired
            // subfield, we will output the different choices available
            echo '<select name="' . $the_subfield['name'] . '">';
            foreach( $the_subfield['choices'] as $k => $v ) {
                echo '<option value="' . $k . '">' . $v . '</option>';
            }
            echo '</select>';
        }
    }
}

我希望它有所帮助!