如何针对指定用户角色与多商品ID隐藏WooCommerce结账页的“寄送到其他地址”
解决WooCommerce多商品ID下隐藏“寄送到其他地址”的问题
你之前的代码在使用多商品ID数组时失效,核心问题是in_array()的参数逻辑错误——你把目标商品ID数组作为要查找的元素,而非查找范围。以下是修正后的代码,同时优化了角色判断的逻辑:
/** Shipping Address */ function filter_woocommerce_cart_needs_shipping_address( $needs_shipping ) { // 目标商品ID数组、用户角色数组 $targeted_product_ids = array(414, 617); $targeted_roles = array('team', 'team2'); // 标记是否找到目标商品 $found = false; // 遍历购物车所有商品 foreach ( WC()->cart->get_cart() as $cart_item ) { // 检查当前商品的ID或变体ID是否在目标数组中 if ( in_array( $cart_item['product_id'], $targeted_product_ids ) || in_array( $cart_item['variation_id'], $targeted_product_ids ) ) { $found = true; break; } } // 如果找到目标商品,且当前用户属于指定角色之一,隐藏寄送到其他地址选项 if ( $found ) { foreach ( $targeted_roles as $role ) { if ( current_user_can( $role ) ) { $needs_shipping = false; break; } } } return $needs_shipping; } add_filter( 'woocommerce_cart_needs_shipping_address', 'filter_woocommerce_cart_needs_shipping_address', 10, 1 );
关键修改说明:
- 调整
in_array()参数顺序:现在是检查购物车项的ID是否存在于目标商品ID数组中,而非反过来 - 将用户角色整合为数组,通过循环简化多次判断的冗余代码
- 保留了原逻辑的核心:找到目标商品且用户符合角色时,设置
$needs_shipping = false来隐藏地址选项
内容的提问来源于stack exchange,提问作者Brienne Friedman
相关产品推荐
相关产品推荐

