如何在 Woocommerce 中使结账账单字段只读

How to Make the Checkout Billing fields read only in Woo Commerce

我们有一个订单网站,然后可以发货。现在的问题是我们想利用我的帐户地址账单中的详细信息作为运送地址,在结账时我们希望从那里填充它,但不允许用户在该结账页面账单表单上进行任何更改。

此代码:

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;
}

仅使地址部分不更改,但可以修改名字、姓氏、手机等其他所有内容。

我们需要锁定所有这些字段,就像将地址字段锁定为只读的代码一样。

您可以删除if($key == 'billing_address_1' || $key == 'billing_address_2'){这一行的所有字段。检查 beloe 代码。

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;
}

对于 billing_countrybilling_statebilling_suburb,您必须在 hidden 中传递值,因为 select 下拉列表已禁用,当您单击位置时不会传递选项值为了解决这个问题,我们可以用我们的值添加隐藏字段。

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" class="input-hidden" name="billing_country"  value="'.get_user_meta($user_id, 'billing_country', true).'">';
    echo '<input type="hidden" class="input-hidden" name="billing_state"  value="'.get_user_meta($user_id, 'billing_state', true).'">';
    echo '<input type="hidden" class="input-hidden" name="billing_suburb"  value="'.get_user_meta($user_id, 'billing_suburb', true).'">';

}

已测试并有效