retrieve_password_notification_email钩子失效,如何发送重置邮件到备用邮箱?
问题分析与修复方案
代码中的核心问题
- 用户ID获取方式错误:
$defaults['user_data']是WP_User实例,获取用户ID需直接访问ID属性,get_the_ID()是文章/页面专用方法,不适用于用户对象。 - 收件人格式错误:
$defaults['to']无需手动添加TO:前缀和换行符,WordPress会自动处理邮件头,只需传入"显示名称 <邮箱地址>"的标准格式即可。 - 缺乏容错逻辑:若用户未设置备用邮箱
ima_email,会导致邮件发送失败,需补充判断避免异常。
修复后的代码
add_filter( 'retrieve_password_notification_email', 'forward_notification_function', 10, 2 ); function forward_notification_function( $defaults, $key ) { // 获取WP_User对象 $user = $defaults['user_data']; // 直接读取用户ID属性 $user_id = $user->ID; // 获取备用邮箱 $notification_email = get_user_meta( $user_id, 'ima_email', true ); // 若无备用邮箱,返回原配置避免发送失败 if ( empty( $notification_email ) ) { return $defaults; } // 获取公司名称,为空则回退使用用户昵称 $name = get_user_meta( $user_id, 'billing_company', true ); $name = empty( $name ) ? $user->display_name : $name; // 设置标准收件人格式 $defaults['to'] = sprintf( '%s <%s>', $name, $notification_email ); return $defaults; }
补充说明
- 钩子注册时指定第三个参数
2,确保函数能接收钩子传递的$defaults和$key两个参数,避免参数缺失导致函数不执行。 - 增加了备用邮箱的空值判断,保证在用户未设置时仍能正常发送邮件到主邮箱。
- 优化了收件人名称的 fallback 逻辑,避免名称为空的情况。
内容的提问来源于stack exchange,提问作者Gonner
相关产品推荐
相关产品推荐

