Я пытаюсь создать динамические раскрывающиеся поля с помощью плагина Ultimate Members. Мне удалось использовать API переписи населения США для создания двух раскрывающихся меню для регистрационной формы, которая заполняет меню штатов, и меню округа, в котором отображаются округа, доступные для каждого штата. В форме регистрации все работает нормально, проблема в том, что когда пользователь отправляет регистрационную форму, название округа, которое отправляется на адрес электронной почты администратора для утверждения учетной записи, пусто (значение штата отправляется правильно.
Я был бы признателен, если бы кто-нибудь указал, где я ошибся. Я использую функцию обратного вызова выбора и добавил следующий код в файл функций.php:
function custom_state_choices_callback() {
// Fetch states from U.S. Census Bureau API
$states_url = 'https://api.census.gov/data/2019/pep/po ... t=NAME...😘';
$response = wp_remote_get($states_url);
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
// Initialize an empty array for states
$states = array();
// Populate the 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);
}
// Function to populate the county dropdown based on the selected state function
custom_county_choices_callback($has_parent = false) {
// Initialize an empty array for counties
$counties = array();
// Get the selected state from the parent field
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);
}
// Fetch counties for each selected state
foreach ($parent_options as $state_code) {
$counties_url = "https://api.census.gov/data/2019/acs/ac ... 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;
}
}
}
}
// Optional: Display this if there are no related options for this choice
if (empty($counties)) {
$counties\[''\] = 'No counties found';
}
return array_unique($counties);
}
// Hook the functions to Ultimate Member's Choices Callback
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
I initially tried creating a custom plugin and using JavaScript to populate the dropdown menus. Everything works in the registration form, but the state and county values were empty in the email that's sent to the admin.
I tried another approach and used the Callback Choices feature and made it one step further with the state value being sent to the admin email, but the county value that's sent to the admin is still empty.
Подробнее здесь: https://stackoverflow.com/questions/788 ... s-callback
Заполнение раскрывающихся меню для плагина Ultimate Members с использованием обратного вызова Choices с внешним API ⇐ Php
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение