Woocommerce county field missing the CSS class `form-control` making it styled different to other textfields
hsankala opened this issue · 5 comments
Understrap v1.2.2
Clean Fresh Install of WordPress 6.1.1
Only Plugins Woocommerce
On the Woocommerce Checkout page (/checkout/) the county field has the incorrect CSS class applied, making it styled different and it looks janky.
On a fresh installation of WordPress and understrap, you'll notice that the County text field is styled differently in the below screenshot
The HTML for this textbox is:
<input type="text" class="input-text " value="" placeholder="" name="billing_state" id="billing_state" data-plugin="select2" data-allow-clear="true" aria-hidden="true" autocomplete="address-level1" data-input-classes="">
It's missing the class form-control
which all other text fields have on this page it makes it look odd and stand out.
Could you suggest a workaround for this I've attempted to look to override the form-checkout.php but this page calls <?php do_action( 'woocommerce_checkout_billing' ); ?>
which appears to be spitting out the HTML form so I can't simply add this missing class.
Add this to your functions.php
add_filter( 'woocommerce_form_field_args', 'slug_state_field_args', 10, 2 );
function slug_state_field_args( $args, $key ) {
if ( 'state' !== $args['type'] ) {
return $args;
}
// Get country.
$country = $args['country'] ?? null;
if ( ! $country ) {
$ctx = $key ? 'billing_country' : 'shipping_country';
$country = WC()->checkout->get_value( $ctx );
}
// Add form-control if country has no states.
if ( false === WC()->countries->get_states( $country ) ) {
if ( isset( $args['input_class'] ) ) {
$args['input_class'][] = 'form-control';
} else {
$args['input_class'] = array( 'form-control' );
}
}
return $args;
}
@IanDelMar Oh you WordPress wizard you, thanks for the workaround!
Your're welcome!
@hsankala You better use this:
add_filter( 'woocommerce_form_field_args', 'slug_state_field_args', 10 );
function slug_state_field_args( $args ) {
if ( 'state' !== $args['type'] ) {
return $args;
}
if ( isset( $args['input_class'] ) ) {
$args['input_class'][] = 'form-control';
} else {
$args['input_class'] = array( 'form-control' );
}
return $args;
}
Reason: WooCommerce uses AJAX to switch between countries. This has the following effect: If on load there is an input[type=text]
field, e.g. for UK, and you select, e.g. US, it shows a select2 state select. Everything works as expected. You can then switch back to UK and the input field is still properly styled. But if on load there is a select2 and you select a country that produces an input[type=text]
field it will not be properly styled.
Adding the form-control
to the input_class
does not change the select2 field but always styles the text input field.