We have a website for orders that are then delivered. Now the thing is we want to utilize the details from the My Account Address Billing as the address to ship to, on checkout we want this populated from what's there but not allow the user to make any changes on that check out page Billing form.
This code:
add_action('woocommerce_checkout_fields','customization_readonly_billing_fields',10,1);
function customization_readonly_billing_fields($checkout_fields){
$current_user = wp_get_current_user();;
$user_id = $current_user->ID;
foreach ( $checkout_fields['billing'] as $key => $field ){
if($key == 'billing_address_1' || $key == 'billing_address_2'){
$key_value = get_user_meta($user_id, $key, true);
if( strlen($key_value)>0){
$checkout_fields['billing'][$key]['custom_attributes'] = array('readonly'=>'readonly');
}
}
}
return $checkout_fields;
}
Only makes the Address part not be changed however everything else from first name, last name, cellphone, etc is able to be modified.
We need all those fields to be locked just as that code as locked the Address field to read-only.
CodePudding user response:
You can remove if($key == 'billing_address_1' || $key == 'billing_address_2'){
this line all fields. check beloe code.
add_action('woocommerce_checkout_fields','customization_readonly_billing_fields',10,1);
function customization_readonly_billing_fields($checkout_fields){
$current_user = wp_get_current_user();
$user_id = $current_user->ID;
foreach ( $checkout_fields['billing'] as $key => $field ){
$key_value = get_user_meta($user_id, $key, true);
if( $key_value != '' ){
if( $key == 'billing_country' || $key == 'billing_state' || $key == 'billing_suburb' ){
$checkout_fields['billing'][$key]['custom_attributes'] = array('disabled'=>'disabled');
}else{
$checkout_fields['billing'][$key]['custom_attributes'] = array('readonly'=>'readonly');
}
}
}
return $checkout_fields;
}
For billing_country
, billing_state
and billing_suburb
, you have to pass value in hidden because the select dropdown disabled the option value is not passed when you click place order and in order to solve this issue we can add hidden fields with our value.
add_action('woocommerce_after_order_notes', 'billing_countryand_state_hidden_field');
function billing_countryand_state_hidden_field($checkout){
$current_user = wp_get_current_user();
$user_id = $current_user->ID;
echo '<input type="hidden" name="billing_country" value="'.get_user_meta($user_id, 'billing_country', true).'">';
echo '<input type="hidden" name="billing_state" value="'.get_user_meta($user_id, 'billing_state', true).'">';
echo '<input type="hidden" name="billing_suburb" value="'.get_user_meta($user_id, 'billing_suburb', true).'">';
}
Tested and works