在WordPress中通过JavaScript Fetch调用wp_mail发邮件问题求助
问题根源与解决方案
核心问题
你遇到的问题本质是前后端数据格式不匹配:前端用JSON.stringify()发送JSON格式的请求体,但PHP的$_POST只能解析application/x-www-form-urlencoded或multipart/form-data格式的数据,导致$_POST['to']等变量为空,自然无法触发正确的邮件发送。另外前端Fetch的写法也有错误,无法正确获取响应。
修复步骤
1. 修正前端Fetch代码
Fetch API不支持success回调,需要用await配合.json()解析响应,同时添加错误捕获:
const submitMail = async () => { try { const rawResponse = await fetch('https://mywordpressinstallation.com/wp-admin/admin-ajax.php?action=mail_before_submit', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({to: 'my-email@gmail.com', title: 'Some title', text: 'some text'}) }); // 解析后端返回的JSON响应 const responseData = await rawResponse.json(); console.log(responseData); // 查看后端返回结果 } catch (error) { console.error('请求失败:', error); } }
2. 修正PHP端参数获取与响应逻辑
从php://input读取JSON数据并解码,同时用wp_send_json返回标准JSON响应(自动处理终止请求):
add_action('wp_ajax_nopriv_mail_before_submit', 'mail_before_submit'); add_action('wp_ajax_mail_before_submit', 'mail_before_submit'); function mail_before_submit() { // 读取并解析JSON请求体 $request_body = file_get_contents('php://input'); $data = json_decode($request_body, true); // 验证必要参数是否存在 if (!isset($data['to'], $data['title'], $data['text'])) { wp_send_json_error(['message' => '缺少必要参数'], 400); } // 清理参数避免注入风险 $to = sanitize_email($data['to']); $title = sanitize_text_field($data['title']); $text = sanitize_textarea_field($data['text']); // 发送邮件并返回结果 $mail_sent = wp_mail($to, $title, $text); if ($mail_sent) { wp_send_json_success(['message' => '邮件发送成功']); } else { wp_send_json_error(['message' => '邮件发送失败']); } }
3. 可选:添加安全验证(重要)
为避免恶意请求,建议添加WordPress nonce验证:
- 前端:在Fetch请求的headers里添加
'X-WP-Nonce': wpApiSettings.nonce(需先在主题/插件中初始化nonce:wp_localize_script('your-script-handle', 'wpApiSettings', ['nonce' => wp_create_nonce('wp_rest')]);) - PHP:在函数开头添加
check_ajax_referer('wp_rest');
验证要点
- 发送请求后,打开浏览器控制台查看
responseData输出,确认后端返回状态 - 可在PHP中用
error_log(print_r($data, true));查看解析后的参数是否正确 - 确保
wp_mail函数本身配置正常(比如WordPress邮件发送设置)
内容的提问来源于stack exchange,提问作者Ivano
相关产品推荐
相关产品推荐

