Support

Account

Home Forums General Issues Disable Options for Select Field Reply To: Disable Options for Select Field

  • With the acf/prepare_field it would work to remove the options for all my requirements.
    So thanks @hube2 for pointing me at that direction.

    I used some different code because i also have optgroups.

    
    function filter_choices($field)
    {
        if (is_user_logged_in() && current_user_can('administrator')) {
            // don't filter for admins
            return $field;
        }
    
        $value = acf_get_array($field['value']);
        $choices = acf_get_array($field['choices']);
    
        // keys which will be removed
        $disabled_options = array(1, 2, 3);
    
        // value should be kept as selectable option for edit therefore remove it from disabled options
        if (!is_null($value)) {
            if (is_array($value)) {
                $disabled_options = array_diff($disabled_options, $value);
            } else {
                $disabled_options = array_diff($disabled_options, array($value));
            }
        }
    
        // delete keys in in normal options
        $choices = array_diff_key($choices, array_flip((array) $disabled_options));
        foreach ($choices as $choice_key => $choice_value) {
            // delete keys in option groups
            if (is_array($choice_value)) {
                $choices[$choice_key] = array_diff_key($choice_value, array_flip((array) $disabled_options));
                //remove empty groups from choices
                if (sizeof($choices[$choice_key])==0) {
                    unset($choices[$choice_key]);
                }
            }
        }
        $field['choices'] = $choices;
        return $field;
    }
    add_filter('acf/prepare_field/name=select_field_name', 'filter_choices', 20);
    

    Anyhow a possibility to disable single options would also be good if this would be implemented in future acf versions.