我试图在wooccommerce中设置Billing_city的默认值,但在结账时,它说city字段是必需的



因为我只在一个城市服务,所以一个城市应该是可见的,但不可编辑。我正在使用此代码

add_filter('woocommerce_billing_fields', 'my_woocommerce_billing_fields');
function my_woocommerce_checkout_fields($fields) {
$fields['billing'] = my_woocommerce_billing_fields($fields['billing']);
return $fields;
}
function my_woocommerce_billing_fields($fields) {
// Note: Default value is only used if the user account does
// not have any value for the meta field yet. (Empty value is
// also a value.) Ensure that the value is set correctly.
$fields['billing_city']['default'] = 'Karachi';
$fields['billing_postcode']['default'] = '75500';
// Disable the field in the form.
// (Note: Does not prevent different values from being posted.)
$fields['billing_city']['custom_attributes']['readonly'] = TRUE;
$fields['billing_city']['custom_attributes']['disabled'] = TRUE;
$fields['billing_postcode']['custom_attributes']['readonly'] = TRUE;
$fields['billing_postcode']['custom_attributes']['disabled'] = TRUE;
return $fields;
}

禁用字段将不会被提交,即使它们有值。

您可以连接到woocommerce_checkout_posted_data过滤器并检查该字段是否不存在,然后添加具有所需值的字段。

// manipulate the posted data
add_filter('woocommerce_checkout_posted_data', 'bt_manipulate_checkout_posted_data');
function bt_manipulate_checkout_posted_data ($data) {
if (empty($data['billing_city'])) $data['billing_city']  = 'Karachi';
return $data;
}

根据需要添加任意数量的字段

相关内容

最新更新