【问题标题】:How to Make the Checkout Billing fields read only in Woo Commerce如何使结帐帐单字段在 Woocommerce 中只读
【发布时间】:2025-12-13 23:05:03
【问题描述】:

我们有一个网站,用于处理随后交付的订单。现在的问题是,我们想利用“我的帐户地址帐单”中的详细信息作为要运送到的地址,在结帐时,我们希望从那里填充该地址,但不允许用户在该结帐页面帐单表格上进行任何更改。

这段代码:

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

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

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

【问题讨论】:

    标签: php wordpress woocommerce checkout billing


    【解决方案1】:

    您可以删除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,您必须在隐藏中传递值,因为选择下拉菜单禁用,当您单击下订单时选项值不会传递,为了解决此问题,我们可以添加隐藏具有我们值的字段。

    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).'">';
    
    }
    

    经过测试且有效

    【讨论】:

    • 非常感谢!这几乎是完美的,唯一没有锁定的是下拉选择列表,可以锁定吗?
    • 我已经更新了我的答案。
    • 仍然下拉显示自己,使用状态和一个称为郊区的自定义。
    • 你能分享你的网站链接吗?
    • 没问题,foodline.co.za