I want to be able to achieve the same thing on the City select field. I want the city to be like the country field with just a normal text or given value that cannot be changed.
Below is my code for the state for woocommerce fields in my function.php. what type should i use?
add_filter( 'woocommerce_checkout_fields', 'custom_checkout_fields', 10, 1 );
function custom_checkout_fields( $fields ) {
$fields['billing']['billing_city']['type'] = 'select';
$fields['billing']['billing_city']['options'] = array('Auckland' => 'Auckland');
return $fields;
}
You can make a field read only (disabled) in checkout page (and also in My account > Adresses > Billing Address section)…
2 different cases:
1) For a select
type:
add_filter( 'woocommerce_billing_fields', 'custom_checkout_billing_city_field', 10, 1 );
function custom_checkout_billing_city_field( $billing_fields ) {
// HERE define the city
$city = 'Auckland';
// Set the city value (to be sure)
WC()->customer->set_billing_city( $city );
// Change the billing city field
$billing_fields['billing_city']['type'] = 'select';
$billing_fields['billing_city']['options'] = array( $city => $city );
$billing_fields['billing_city']['default'] = $city;
$billing_fields['billing_city']['custom_attributes']['disabled'] = 'disabled';
return $billing_fields;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
The select field is disabled (read only) with the preselected city:
2) For a text
type:
add_filter( 'woocommerce_billing_fields', 'custom_checkout_billing_city_field', 10, 1 );
function custom_checkout_billing_city_field( $billing_fields ) {
// HERE define the city
$city = 'Auckland';
// Set the city value (to be sure)
WC()->customer->set_billing_city( $city );
// Change the billing city field
$billing_fields['billing_city']['default'] = $city;
$billing_fields['billing_city']['custom_attributes']['readonly'] = 'readonly';
return $billing_fields;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
The text field is read only with the preselected city: