Using Gravity Forms ‘gform_field_css_class’ PHP action

The gform_field_css_class filter in Gravity Forms PHP allows you to dynamically add or remove CSS classes to a field.

Usage

To use this filter, add the following line of code to your theme’s functions.php file:

add_filter('gform_field_css_class', 'custom_class', 10, 3);

If you want to apply this filter only to a specific form, include the form ID after the hook name:

add_filter('gform_field_css_class_6', 'custom_class', 10, 3);

Parameters

  • $classes (string): The CSS classes to be filtered, separated by empty spaces (e.g., “gfield custom_class”).
  • $field (Field Object): The current field.
  • $form (Form Object): The current form.

More information

See Gravity Forms Docs: gform_field_css_class

Examples

Add a custom class to all text fields

This example adds a custom CSS class to all text fields in the form.

add_filter('gform_field_css_class', 'custom_class', 10, 3);
function custom_class($classes, $field, $form) {
    if ($field->type == 'text') {
        $classes .= ' custom_textfield_class';
    }
    return $classes;
}

Add a custom class to a specific field by ID

This example adds a custom CSS class to a specific field with the field ID of 2.

add_filter('gform_field_css_class', 'add_custom_class_to_field', 10, 3);
function add_custom_class_to_field($classes, $field, $form) {
    if ($field->id == 2) {
        $classes .= ' custom_class_for_field_2';
    }
    return $classes;
}

Add a custom class to required fields

This example adds a custom CSS class to all required fields in the form.

add_filter('gform_field_css_class', 'add_custom_class_to_required_fields', 10, 3);
function add_custom_class_to_required_fields($classes, $field, $form) {
    if ($field->isRequired) {
        $classes .= ' custom_required_field_class';
    }
    return $classes;
}

Remove a specific class from all fields

This example removes a specific CSS class from all fields in the form.

add_filter('gform_field_css_class', 'remove_specific_class', 10, 3);
function remove_specific_class($classes, $field, $form) {
    $classes = str_replace('class_to_remove', '', $classes);
    return $classes;
}

Add custom classes based on field type

This example adds different custom CSS classes depending on the field type.

add_filter('gform_field_css_class', 'add_custom_class_based_on_field_type', 10, 3);
function add_custom_class_based_on_field_type($classes, $field, $form) {
    switch ($field->type) {
        case 'text':
            $classes .= ' custom_textfield_class';
            break;
        case 'checkbox':
            $classes .= ' custom_checkbox_class';
            break;
        case 'select':
            $classes .= ' custom_select_class';
            break;
    }
    return $classes;
}