首页 > 解决方案 > 如何使结帐帐单字段在 Woo Commerce 中只读

问题描述

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

这段代码:

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

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

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

标签: phpwordpresswoocommercecheckoutbilling

解决方案


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

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_country,billing_statebilling_suburb,您必须在 hidden 中传递值,因为当您单击下订单时,选择下拉菜单禁用了选项值,为了解决这个问题,我们可以使用我们的值添加隐藏字段。

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

}

测试和工作

在此处输入图像描述


推荐阅读