【问题标题】:ACF Dynamically populate a select field’s choices - not completely workingACF 动态填充选择字段的选项 - 不完全工作
【发布时间】:2020-08-27 22:17:45
【问题描述】:

这是我的代码示例:

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

【问题讨论】:

    标签: php wordpress advanced-custom-fields


    【解决方案1】:

    [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();
    

    如您所见,我还检查了数组是否相等,如果相等则不更新。但我认为修剪(去除尾随回报)是诀窍。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-24
      • 2013-07-22
      • 1970-01-01
      相关资源
      最近更新 更多