WooCommerce:购物车中只有虚拟商品时,移除不必要的结账字段

如果我们使用 WooCommerce 发布了一个虚拟产品——如付费下载资源,用户购买后,可以直接下载,不需要发送商品或账单给顾客,这个时候,结账页面的收件地址字段明显是多余的。

如果结账时, 顾客的订单中只有虚拟商品时,我们可以移除收货地址字段,减少要求用户填写的内容,以提高结账效率。实现这个需求的关键是判断购物车中只有虚拟商品。

我们可以遍历购物车中的商品来进行判断,只要有一个商品不是虚拟商品,移除收货地址字段这个条件就不成立,具体参考下面的代码。


add_filter('woocommerce_checkout_fields', function ($fields)
{

    $only_virtual = true;

    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
        // Check if there are non-virtual products
        if ( ! $cart_item[ 'data' ]->is_virtual()) {
            $only_virtual = false;
        }
    }

    if ($only_virtual) {
        unset($fields[ 'billing' ][ 'billing_first_name' ]);
        unset($fields[ 'billing' ][ 'billing_last_name' ]);
        unset($fields[ 'billing' ][ 'billing_email' ]);
        unset($fields[ 'billing' ][ 'billing_company' ]);
        unset($fields[ 'billing' ][ 'billing_address_1' ]);
        unset($fields[ 'billing' ][ 'billing_address_2' ]);
        unset($fields[ 'billing' ][ 'billing_city' ]);
        unset($fields[ 'billing' ][ 'billing_postcode' ]);
        unset($fields[ 'billing' ][ 'billing_country' ]);
        unset($fields[ 'billing' ][ 'billing_state' ]);
        unset($fields[ 'billing' ][ 'billing_phone' ]);
        add_filter('woocommerce_enable_order_notes_field', '__return_false');
    }

    return $fields;
});