Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[WooCommerce] 根據選擇運送方式修改結帳欄位的方法 https://www.mxp.tw/8640/
<?php
function mxp_hidden_checkout_fields_base_on_shipping_method($value) {
// 判斷當前選擇到的運送方式
$chosen_methods = WC()->session->get('chosen_shipping_methods');
$chosen_shipping = current(explode(':', $chosen_methods[0]));
if ($chosen_shipping == 'local_pickup') {
$fields = WC()->checkout->get_checkout_fields('billing');
$html = "";
foreach ($fields as $key => $field) {
$field['return'] = true;
// 判斷對應需要調整的欄位來改參數重新產生欄位結構輸出
if ($key == 'billing_postcode' || $key == 'billing_address_1' || $key == 'billing_state' || $key == 'billing_city') {
$field['class'] = array('hidden');
$field['type'] = 'hidden';
$field['required'] = false;
}
$html .= woocommerce_form_field($key, $field, WC()->checkout->get_value($key));
}
$value['.woocommerce-billing-fields__field-wrapper'] = '<div class="woocommerce-billing-fields__field-wrapper">' . $html . '</div>';
} else {
// 不符合條件的舊照常輸出
$fields = WC()->checkout->get_checkout_fields('billing');
$html = "";
foreach ($fields as $key => $field) {
$field['return'] = true;
$html .= woocommerce_form_field($key, $field, WC()->checkout->get_value($key));
}
$value['.woocommerce-billing-fields__field-wrapper'] = '<div class="woocommerce-billing-fields__field-wrapper">' . $html . '</div>';
}
return $value;
}
add_filter('woocommerce_update_order_review_fragments', 'mxp_hidden_checkout_fields_base_on_shipping_method', 999, 1);
function mxp_checkout_fields_modify_base_on_shipping_method($fields) {
//讀取當前選擇的運送方式方法
$chosen_methods = WC()->session->get('chosen_shipping_methods');
//因為取得的是某個方法,而不是某種方法,所以要拆解一下。我知道這邊有點難懂,請搭配下文補充
$chosen_shipping = current(explode(':', $chosen_methods[0]));
//判斷是否符合自取條件
if ($chosen_shipping == 'local_pickup') {
//使用覆寫的方式,不是重新建立,重新建立反而可能會有其他問題!
$fields['billing']['billing_postcode']['required'] = false;
$fields['billing']['billing_postcode']['class'] = array('hidden');
$fields['billing']['billing_postcode']['type'] = 'hidden';
$fields['billing']['billing_address_1']['required'] = false;
$fields['billing']['billing_address_1']['class'] = array('hidden');
$fields['billing']['billing_address_1']['type'] = 'hidden';
$fields['billing']['billing_state']['required'] = false;
$fields['billing']['billing_state']['class'] = array('hidden');
$fields['billing']['billing_state']['type'] = 'hidden';
$fields['billing']['billing_city']['required'] = false;
$fields['billing']['billing_city']['class'] = array('hidden');
$fields['billing']['billing_city']['type'] = 'hidden';
}
return $fields;
}
add_filter('woocommerce_checkout_fields', 'mxp_checkout_fields_modify_base_on_shipping_method', 999, 1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.