WooCommerce如何设置仅需注册的商品结算时强制要求填写邮箱
解决方案
你可以直接替换原有代码为以下内容,即可实现仅当结算商品为需要注册的WooCommerce Membership会员商品时,邮箱字段才设为必填:
add_filter( 'woocommerce_billing_fields', 'customize_billing_email_required_rule' ); function customize_billing_email_required_rule( $fields ) { // 默认邮箱为非必填 $email_required = false; // 兼容判断:避免插件未启用时报错 if ( function_exists( 'wc_memberships_is_product_associated_with_membership_plan' ) && ! is_null( WC()->cart ) ) { // 遍历购物车所有商品 foreach ( WC()->cart->get_cart() as $item ) { // 检测商品是否关联会员计划(即你定义的需要注册的商品) if ( wc_memberships_is_product_associated_with_membership_plan( $item['product_id'] ) ) { $email_required = true; break; } } } $fields['billing_email']['required'] = $email_required; return $fields; }
逻辑说明
- 购物车全为普通商品时,邮箱字段保持非必填状态
- 只要购物车中存在1个关联了会员计划的商品,邮箱字段自动切换为必填
- 前置的函数存在判断可避免WooCommerce Membership插件停用后网站报错
内容的提问来源于stack exchange,提问作者gpante
相关产品推荐
相关产品推荐

