You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:将表单提交从php mail()切换为wp_mail()的实现方法

修改方案

直接替换原生mail()函数为WordPress的wp_mail()即可,同时调整细节适配WP环境,修改后的代码如下:

<?php
// 若代码运行在WordPress主题/插件中,建议移除session_start(),改用WP内置的nonce验证防止重复提交
// session_start();
if(!isset($_SESSION['set']))
{
    $_SESSION['set'] = 1;
    $oConnect       = mysqli_connect('localhost', 'userlogin', 'userpass');
    $content    = str_replace(array_keys($replace), array_values($replace), $content);

    // 从数据库获取数据

    $to         = $_POST['txt_email']; 
    $subject    = 'Your request';
    // 保持标准邮件头格式,wp_mail兼容该格式
    $headers    = "From: info@domainexample.com\r\n";
    $headers    .= "Bcc: info@domainexample.com\r\n";
    $headers    .= "Reply-To: info@domainexample.com\r\n";
    $headers    .= "MIME-Version: 1.0\r\n";
    $headers    .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
    // 替换原生mail()为wp_mail()
    if(!empty($to)){
       wp_mail($to, $subject, $content, $headers); 
    }
}
?>

关键修改点

  • 核心替换:将mail($to,$subject,$content,$headers)直接替换为wp_mail($to,$subject,$content,$headers),两者参数顺序完全一致,无需调整参数结构。
  • 邮件头优化:把原代码中的换行统一改为\r\n(标准邮件头换行格式,避免部分服务器解析异常)。
  • 可选规范优化:如果这段代码用于WordPress主题或插件,建议移除session_start(),改用WordPress内置的nonce验证机制(表单中添加wp_nonce_field(),处理时用wp_verify_nonce()验证),更符合WP开发规范。

注意事项

  • 确保代码运行在WordPress环境中:如果是独立PHP文件,需在开头添加require_once($_SERVER['DOCUMENT_ROOT'].'/wp-load.php');加载WordPress核心,否则wp_mail()会报错。
  • 你已配置好WP Mail SMTP插件,无需额外调整插件设置,wp_mail()会自动调用插件的SMTP配置发送邮件。

内容的提问来源于stack exchange,提问作者Steven83

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 21:22:40