Ultimate Members插件动态下拉提交后County值为空问题求助
问题分析与解决方案
问题根源
管理员审批邮件中县名称为空的核心原因是:邮件生成时没有表单提交的$_POST上下文,你的custom_county_choices_callback函数依赖$_POST['parent_option']获取选中的州来加载对应县,但邮件渲染阶段该值不存在,导致函数返回的选项列表中没有用户选中的县,Ultimate Members无法匹配到对应的标签,最终显示为空。
修复代码
修改你的回调函数,使其支持从用户已保存的元数据中获取州值,而非仅依赖$_POST:
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,STATE&for=state:*'; $response = wp_remote_get($states_url); if (is_wp_error($response)) return []; $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; $state_code = $state[1]; $state_name = $state[0]; $states[$state_code] = $state_name; } } return array_unique($states); } function custom_county_choices_callback($has_parent = false, $saved_state_code = null) { $counties = array(); $state_codes = array(); // 优先使用传入的已保存州值,其次从POST获取 if ($saved_state_code) { $state_codes[] = $saved_state_code; } elseif ($has_parent && isset($_POST['parent_option'])) { $parent_options = $_POST['parent_option']; $state_codes = is_array($parent_options) ? $parent_options : array($parent_options); } foreach ($state_codes 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); if (is_wp_error($response)) continue; $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; $county_name = explode(',', $county[0])[0]; $counties[$county_name] = $county_name; } } } 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') { // 从用户元数据中获取已保存的州值(邮件/资料页场景) $saved_state = null; if (isset($GLOBALS['um_user']) && $GLOBALS['um_user'] instanceof WP_User) { $saved_state = get_user_meta($GLOBALS['um_user']->ID, 'service_state', true); } elseif (isset($_GET['user_id'])) { $saved_state = get_user_meta(intval($_GET['user_id']), 'service_state', true); } $choices = custom_county_choices_callback(true, $saved_state); } return $choices; }, 10, 2);
额外优化建议
- 缓存API请求结果:使用
wp_cache_set和wp_cache_get缓存州/县数据,避免频繁调用Census API,提升性能。 - 错误处理增强:在API请求失败时,返回友好的提示或默认值,避免字段加载异常。
内容的提问来源于stack exchange,提问作者Lindy Ramirez
相关产品推荐
相关产品推荐

