如何在WooCommerce中设置特定产品仅配送至指定国家?
在WooCommerce中设置特定产品仅配送至特定国家(以美国为例)
嘿,这个需求我之前帮不少用户处理过,不用额外插件,靠WooCommerce自带的钩子就能搞定,分步骤来给你说清楚:
第一步:给产品添加「仅配送至美国」的自定义开关
首先我们要给需要限制的产品加个标记,这样你在编辑产品时就能快速勾选哪些产品需要限制配送范围。把下面的代码添加到主题的functions.php文件里,或者用「Code Snippets」这类自定义代码插件(更推荐后者,避免主题更新丢失代码):
// 在产品编辑页的库存选项卡下添加自定义勾选框 add_action( 'woocommerce_product_options_inventory_product_data', 'add_restrict_to_usa_checkbox' ); function add_restrict_to_usa_checkbox() { woocommerce_wp_checkbox( array( 'id' => '_restrict_to_usa', 'label' => __( '仅配送至美国', 'woocommerce' ), 'description' => __( '勾选后,该产品仅允许配送至美国地区', 'woocommerce' ) ) ); } // 保存产品的勾选状态 add_action( 'woocommerce_process_product_meta', 'save_restrict_to_usa_checkbox_value' ); function save_restrict_to_usa_checkbox_value( $post_id ) { $checkbox_state = isset( $_POST['_restrict_to_usa'] ) ? 'yes' : 'no'; update_post_meta( $post_id, '_restrict_to_usa', $checkbox_state ); }
添加完代码后,你去编辑任意产品,就能在「库存」选项卡下方看到这个勾选框了,勾选它就标记了该产品仅能配送至美国。
第二步:结账环节验证国家并显示提示
接下来我们要在结账时检查用户选择的配送国家,如果购物车里有标记过的受限产品,且用户选的不是美国,就弹出你要的提示信息。继续添加下面的代码:
// 结账时验证配送国家 add_action( 'woocommerce_checkout_process', 'validate_checkout_for_restricted_products' ); function validate_checkout_for_restricted_products() { // 先检查购物车中是否有受限产品 $has_restricted_item = false; foreach ( WC()->cart->get_cart() as $cart_item ) { $product = $cart_item['data']; if ( get_post_meta( $product->get_id(), '_restrict_to_usa', true ) === 'yes' ) { $has_restricted_item = true; break; } } // 如果有受限产品,且用户选择的国家不是美国,抛出错误提示 if ( $has_restricted_item && WC()->customer->get_shipping_country() !== 'US' ) { wc_add_notice( __( 'We cannot deliver to your country.', 'woocommerce' ), 'error' ); } }
可选:在购物车页面提前提示用户
为了提升用户体验,你可以在购物车页面就显示提示,避免用户到结账环节才发现问题。添加这段代码:
// 购物车页面显示配送限制提示 add_action( 'woocommerce_cart_totals_before_shipping', 'show_restriction_notice_in_cart' ); function show_restriction_notice_in_cart() { $has_restricted_item = false; foreach ( WC()->cart->get_cart() as $cart_item ) { $product = $cart_item['data']; if ( get_post_meta( $product->get_id(), '_restrict_to_usa', true ) === 'yes' ) { $has_restricted_item = true; break; } } if ( $has_restricted_item && WC()->customer->get_shipping_country() !== 'US' ) { echo '<div class="woocommerce-error">We cannot deliver to your country.</div>'; } }
扩展说明
- 如果需要限制多个国家,比如美国和加拿大,只需要把代码里的
WC()->customer->get_shipping_country() !== 'US'改成!in_array( WC()->customer->get_shipping_country(), array('US', 'CA') )就行。 - 代码里的国家代码是WooCommerce标准的两位ISO代码,比如英国是
GB,德国是DE。
内容的提问来源于stack exchange,提问作者AlexMcowkin




