Home / Admin / Address field – make State field optional
Duplicate Snippet

Embed Snippet on Your Site

Address field – make State field optional

Ralden Souza PRO
<10
Code Preview
php
<?php
add_filter( 'wpforms_field_properties', 'custom_address_state_optional', 10, 3 );
function custom_address_state_optional( $properties, $field, $form_data ) {
    // Check if the field is an Address field.
    if ( 'address' === $field['type'] ) {
        // Set the 'required' property of the 'state' subfield to false.
        $properties['inputs']['state']['required'] = false;
        // Remove the 'required' attribute from the 'state' subfield.
        if ( isset( $properties['inputs']['state']['attr']['required'] ) ) {
            unset( $properties['inputs']['state']['attr']['required'] );
        }
        // Remove the 'aria-required' attribute from the 'state' subfield.
        if ( isset( $properties['inputs']['state']['attr']['aria-required'] ) ) {
            unset( $properties['inputs']['state']['attr']['aria-required'] );
        }
        // Remove the 'wpforms-field-required' class from the 'state' subfield.
        if ( isset( $properties['inputs']['state']['class'] ) ) {
            $properties['inputs']['state']['class'] = str_replace( ' wpforms-field-required', '', $properties['inputs']['state']['class'] );
            $properties['inputs']['state']['class'] = str_replace( 'wpforms-field-required', '', $properties['inputs']['state']['class'] );
        }
        // Remove the 'wpforms-required-label' class from the 'state' subfield label.
        if ( isset( $properties['inputs']['state']['label']['class'] ) ) {
            $properties['inputs']['state']['label']['class'] = str_replace( ' wpforms-required-label', '', $properties['inputs']['state']['label']['class'] );
            $properties['inputs']['state']['label']['class'] = str_replace( 'wpforms-required-label', '', $properties['inputs']['state']['label']['class'] );
        }
    }
    return $properties;
}

Comments

Add a Comment