WooCommerce根据用户选择的物流/快递方式隐藏账单/收货地址字段

在WooCommerce的结账流程设计中,系统默认认为用户在网站上购买商品需要发货到用户指定的地址。这也是标准的电商流程。当然、也有一些特殊情况,比如虚拟商品不需要发货的、用户选择发送到指定自提点的,这些情况都不需要用户输入所有的账单/收货地址字段。

用户选择物流方式后,在前端显示/隐藏某些字段

下面的代码示例中,当用户选择了本地取货的支付方式后,隐藏了公司、国家、地址行1、地址行2、城市、州/省份、邮编这些不必填写的收货地址字段。然后从平台给出的一些自提点中选择一个作为收货地址,系统把商品配送到这个自提点后,会通知用户去提货。

jQuery(document).ready(function($) {

    /**
     * 用户选择了某个支付方式后,显示或隐藏某些字段
     */
    var wclp_show_address_button = function() {
        var selected_method = $('input[name^="shipping_method"][type="radio"]:checked').val(),
            address_fields = $(
      '#billing_company_field,#billing_country_field,#billing_address_1_field,#billing_address_2_field, #billing_city_field, #billing_state_field, #billing_postcode_field');

        if (selected_method === 'wclp_shipping_method') {
            address_fields.hide();
        } else {
            address_fields.show();
        }

    };

    /**
     * 用户修改支付方式后
     */
    $(document).on('change', 'input[name^="shipping_method"][type="radio"]', function(event) {
        wclp_show_address_button();
    });

    /**
     * 更新购物车后
     */
    $(document.body).on('updated_checkout', function(data) {
        wclp_show_address_button();
    });

    wclp_show_address_button();
});

从后端移除某些必填的收货地址字段

WooCommerce 的收件地址字段中、有些是必填的,比如省份、城市、邮编、地址这些信息。第一步的代码中,我们只是从前端隐藏了这些字段,如果后端不做处理,用户选择自提点、点击提交后,系统会提示某些必填字段没有填写(因为这些字段是隐藏的,用户根本找不到填写的字段)。

这个时候,我们需要从后端把这些必填字段移除,以避免出现上面的错误。下面的代码中,我们移除了地址行1、州/省份、城市、邮编这些必填字段。

add_filter('woocommerce_checkout_fields', function ($fields)
{
    $chosen_methods  = WC()->session->get('chosen_shipping_methods');
    $chosen_shipping = $chosen_methods[ 0 ];

    if ($chosen_shipping == 'wclp_shipping_method') {
        unset($fields[ 'billing' ][ 'billing_address_1' ]);
        unset($fields[ 'billing' ][ 'billing_state' ]);
        unset($fields[ 'billing' ][ 'billing_city' ]);
        unset($fields[ 'billing' ][ 'billing_postcode' ]);
    }

    return $fields;
}, 990);

除了根据用户选择的物流方式,我们还可以根据用户购买的商品,选择性的移除某些字段,比如。

资源分享 本站提供不断更新优质资源,敬请收藏关注
玄武新动力 » WooCommerce根据用户选择的物流/快递方式隐藏账单/收货地址字段

提供最优质的资源集合

立即查看 了解详情