WooCommerce仅当客户邮编不为空时触发wc_add_notice通知的实现咨询
WooCommerce 配送区域最低金额校验修复方案
核心修改逻辑
- 新增邮编优先级校验,未填写邮编时直接触发输入提示,不会默认匹配1区规则
- 邮编填写完成后再执行原有配送区域匹配、最低订单金额校验逻辑
修复后完整代码
//MINIMUM CART AMOUNT FOR CHECKOUT add_action( 'woocommerce_check_cart_items', 'required_min_cart_subtotal_amount' ); function required_min_cart_subtotal_amount() { // 原有冗余代码可直接注释,无实际作用 // $zone = WC_Shipping_Zones::get_zone_by ( 'zone_name', "1" . 'zone_name', "2" . 'zone_name' , "3" ); // Only run it in Cart or Checkout pages if( is_cart() || ( is_checkout() && ! is_wc_endpoint_url() ) ) { // Get cart shipping packages $shipping_packages = WC()->cart->get_shipping_packages(); $first_package = reset( $shipping_packages ); // 新增:校验用户是否已填写邮编 $customer_postcode = $first_package['destination']['postcode'] ?? ''; if( empty( trim( $customer_postcode ) ) ) { wc_add_notice( __("Please enter your postcode"), 'error' ); remove_action( 'woocommerce_proceed_to_checkout','woocommerce_button_proceed_to_checkout', 20); return; } //Get the WC_Shipping_Zone instance object for the first package $shipping_zone = wc_get_shipping_zone( $first_package ); $zone_id = $shipping_zone->get_id(); //Get the zone ID $zone_name = $shipping_zone->get_zone_name(); // Get the zone name // Total (before taxes and shipping charges) $total = WC()->cart->subtotal; // HERE set minimum cart total amount (for Zone 1,2,3 and for other zones) $min_total = 180; if ($zone_id == "2") $min_total = 100; if ($zone_id == "3") $min_total = 220; // Add an error notice if cart total is less than the minimum required if( $total <= $min_total ) { // Display an error message wc_add_notice( sprintf( __("A minimum order of - %s is required. Please enter your Postal Code in the Shipping section below. Minimum orders differ from area to area."), wc_price( $min_total) ), 'error' ); remove_action( 'woocommerce_proceed_to_checkout','woocommerce_button_proceed_to_checkout', 20); } add_action( 'woocommerce_proceed_to_checkout', 'disable_checkout_button', 1); } }
效果验证
- 新访客未填写邮编进入购物车页面时,仅展示「Please enter your postcode」提示
- 填写邮编并提交配送地址信息后,自动匹配对应区域的最低金额要求
- 订单金额不满足对应区域要求时,展示原有区域对应的最低金额提示
内容的提问来源于stack exchange,提问作者Linda Rabie
相关产品推荐
相关产品推荐

