Using Gravity Forms ‘gform_field_choices’ PHP filter

The gform_field_choices filter is executed when creating the checkbox or radio button items. It can be used to manipulate the item’s string before it gets added to the checkbox or radio button list.

Usage

add_filter('gform_field_choices', 'your_custom_function', 10, 2);

Parameters

  • $choices (string) – The string containing the choices to be filtered, e.g. <option>Item 1</option><option>Item 2</option>
  • $field (Field Object) – The current field

More information

See Gravity Forms Docs: gform_field_choices

Examples

Allow HTML characters in checkbox and radio items

add_filter('gform_field_choices', 'decode_specialchars', 10, 2);

function decode_specialchars($choices, $field) {
    $choices = htmlspecialchars_decode($choices);
    return $choices;
}

Add a custom CSS class to all radio button items

add_filter('gform_field_choices', 'add_custom_css_class', 10, 2);

function add_custom_css_class($choices, $field) {
    if ($field->type == 'radio') {
        $choices = str_replace('<li>', '<li class="custom-radio-item">', $choices);
    }
    return $choices;
}

Add custom data attributes to checkbox items

add_filter('gform_field_choices', 'add_data_attributes', 10, 2);

function add_data_attributes($choices, $field) {
    if ($field->type == 'checkbox') {
        $choices = str_replace('<input', '<input data-custom-attr="example"', $choices);
    }
    return $choices;
}

Pre-select the first choice in radio buttons

add_filter('gform_field_choices', 'preselect_first_radio', 10, 2);

function preselect_first_radio($choices, $field) {
    if ($field->type == 'radio') {
        $choices = str_replace('value="1"', 'value="1" checked', $choices);
    }
    return $choices;
}

Add custom text to the beginning of each checkbox item

add_filter('gform_field_choices', 'add_prefix_to_checkbox', 10, 2);

function add_prefix_to_checkbox($choices, $field) {
    if ($field->type == 'checkbox') {
        $choices = str_replace('<label>', '<label>Prefix: ', $choices);
    }
    return $choices;
}