Hi everybody,
I’m trying to create dynamic dropdown fields using the Ultimate Members plugin. I’ve managed to use the US Census api to create two drop down menus for a registration form that populates a states menu, and a county menu that gets the counties available for each state. Everything works fine in the registration form, the problem is that when the user submits the registration form the county name that is sent to the admin email for account approval is empty(the state value is being sent correctly. I would appreciate it if somebody could point out where I went wrong. I’m using the choices callback feature and have added the following code to my themes functions.php file:
function custom_state_choices_callback() {
// Fetch states from U.S. Census Bureau API
$states_url = 'https://api.census.gov/data/2019/pep/population?get=NAME…😘';
$response = wp_remote_get($states_url);
$body = wp_remote_retrieve_body($response); $data = json_decode($body, true);
$states = array();
if (!empty($data) && is_array($data)) {
foreach ($data as $index => $state) {
if ($index === 0) continue; // Skip the header row
$state_code = $state[1];
$state_name = $state[0];
$states[$state_code] = $state_name;
}
}
return array_unique($states);
}
custom_county_choices_callback($has_parent = false) {
// Initialize an empty array for counties
$counties = array();
if ($has_parent) {
// Get the selected state from the parent field
$parent_options = isset($_POST['parent_option']) ? $_POST['parent_option'] : array();
if (!is_array($parent_options)) {
$parent_options = array($parent_options);
}
foreach ($parent_options as $state_code) {
$counties_url = "https://api.census.gov/data/2019/acs/acs5?get=NAME&for=county:*&in=state:$state_code";
$response = wp_remote_get($counties_url);
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
if (!empty($data) && is_array($data)) {
foreach ($data as $index => $county) {
if ($index === 0) continue; // Skip the header row
$county_name = explode(',', $county[0])[0];
$counties[$county_name] = $county_name;
}
}
}
}
if (empty($counties)) {
$counties[''] = 'No counties found';
}
return array_unique($counties);
}
add_filter('um_custom_field_choices_callback', function($choices, $field)
{ if ($field['meta_key'] === 'service_state') {
$choices = custom_state_choices_callback();
} elseif ($field['meta_key'] === 'service_county') {
$choices = custom_county_choices_callback(true); }
return $choices; }, 10, 2);
TIA

If the form is populating correctly, then this isn’t related to the api at all. Look at the form fields in the html. Does UM require the custom fields to be registered somewhere? Perhaps it’s striping them if they aren’t set up as custom fields. Are the county fields actually submitting? (Check using DevTools)
You should be caching that data btw. Use a transient.