问题描述
这是我的代码示例:
function acf_populate_age_select( $field ) {
//Get the values from textarea on option page
$site_settings = get_field('theme_settings','option');
$exhibitor_options = $site_settings[0]['exhibitor_options'];
//Turn the values in to an array
$ages = explode(PHP_EOL,$exhibitor_options['age_groups']);
//Clear the choices
$field['choices'] = array();
//Repopulate $field['choices']
foreach ( $ages as $age ) {
$field['choices'][$age] = $age;
}
return $field;
}
add_filter( "acf/load_field/key=field_5f451fd1af75e",'acf_populate_age_select' );
以以下示例为例:
https://www.advancedcustomfields.com/resources/dynamically-populate-a-select-fields-choices/
我正在尝试从选项页面中的textarea字段填充加载时的下拉字段的值。它填充得很好,但我遇到了一些问题。
我遇到的错误是:
-
如果我先清除$ field ['choices'],然后重新填充它,然后在数据库页面上的选定值正确的情况下,它将重置为编辑器中的第一个值,就像保存该值一样但下拉菜单在加载后会被重写
-
如果我不先清除选择,即使在数据库或WP后端中找不到旧值,旧值仍会保留在下拉列表中,成为幻影
任何人都可以看到我在做什么错吗,或者知道我可以尝试如何使下拉列表填充然后突出显示数据库中当前选择的值吗?
我在wordpress v5.5上使用ACF Pro v5.9
解决方法
[palmface],所以看来这是重要的一行:
// remove any unwanted white space
$choices = array_map('trim',$choices);
对于上述问题,
//Turn the values in to an array
$ages = explode(PHP_EOL,$exhibitor_options['age_groups']);
$ages = array_map('trim',$ages);
if($ages === $field['choices'])
return $field;
//Clear the choices
$field['choices'] = array();
如您所见,我还检查了数组是否相等,如果相等,则不更新。但是我认为调整(以消除尾随收益)是窍门。