Your Location is: Home > Php

ACF: Dynamically populate select options based on Json Endpoint

From: Albania View: 4705 Apphut 

Question

I think I am close, I am trying to get some Json Data in the following format below transformed into ACF select fields choices. I need to populate the dropdownlist with api data on load in the back end of wordpress

{
id: "ADSSASASASASA",
name: "Name1",
description: "",
code: "",
defaultDonationAmount: 0
},
{
id: "FDFDFDFDDF",
name: "Name2",
description: "",
code: "",
defaultDonationAmount: 0
},
{
id: "RREERERERERERERE",
name: "Name3",
description: "",
code: "",
defaultDonationAmount: 0
},
]


And

assign field['choices'] and array with the data in this form

$field['choices'] = [
        'id' => 'name',
        'id' => 'name',
        'id' => 'name'
    ];


$url = "https://urltojsondata";
$json = file_get_contents($url);
$json_data = json_decode($json, true);

$field['choices'] = array_map(function($item){return [$item['id'] $item['name']];}, $json_data);
return $field;

Best answer