WooCommerce: Disabling checkout fields with a filter hook

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-06 16:49:30

问题


I have try to disable the "required" property of several checkout fields at the same time using woocommerce_checkout_fields filter hook, with no success.

Plugins are not working properly either. This is my code:

// Hook in
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );

// Our hooked in function - $fields is passed via the filter!
function custom_override_checkout_fields( $fields ) {
$fields['billing']['billing_address_1']['required'] = false;
$fields['billing']['billing_address_2']['required'] = false;

$fields['billing']['billing_postcode']['required'] = false;
$fields['billing']['billing_city']['required'] = false;
$fields['billing']['billing_phone']['required'] = false;

     return $fields;
}

What is wrong?
How can I achieve this?


回答1:


You need to use the unset() function for this purpose and you can do-it this way:

add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );

function custom_override_checkout_fields( $fields ) {
    unset($fields['billing']['billing_address_1']);
    unset($fields['billing']['billing_address_2']);
    unset($fields['billing']['billing_postcode']);
    unset($fields['billing']['billing_city']);
    unset($fields['billing']['billing_phone']);
    return $fields;
}

You will need to paste this code in function.php file located in your active child theme or theme.


You have changed your question with an update: Here it is my new answer

Making the address fields optional (regarding your update):

You have to use a different filter hook for that purpose. There are 2 different filter hooks:

1) For Billing Fields:

add_filter( 'woocommerce_billing_fields', 'wc_optional_billing_fields', 10, 1 );
function wc_optional_billing_fields( $address_fields ) {
    $address_fields['billing_address_1']['required'] = false;
    $address_fields['billing_address_2']['required'] = false;
    $address_fields['billing_postcode']['required'] = false;
    $address_fields['billing_city']['required'] = false;
    $address_fields['billing_phone']['required'] = false;
    return $address_fields;
}

2) For shipping fields:

add_filter( 'woocommerce_shipping_fields', 'wc_optional_shipping_fields', 10, 1 );
function wc_optional_shipping_fields( $address_fields ) {
    $address_fields['shipping_phone']['required'] = false;
    return $address_fields;
}

To make the address fields required:

You can use the same hooks and functions above, changing for each field false to true.


You will need to paste this code in function.php file located in your active child theme or theme.

Reference: Customizing checkout fields using hooks



来源:https://stackoverflow.com/questions/37791580/woocommerce-disabling-checkout-fields-with-a-filter-hook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!