如何通过php处理wordpress表单?

How to handle wordpress forms via php?

提问人:pgalle 提问时间:10/6/2023 最后编辑:pgalle 更新时间:10/6/2023 访问量:27

问:

我的 wordpress 网站上有一个联系表格,我正在尝试相应地发送电子邮件。但是,既没有向客户端发送电子邮件,也没有向客户端发送回复。即使一开始没有条件,它也不起作用。我没有收到任何关于此问题的服务器日志。

我做错了什么?

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() {
    $jsonRequest = json_decode(file_get_contents('php://input'), true);
    if (strcmp($jsonRequest['action'], 'contact_form') !== 0) {
        echo 'failure';
        exit(1);
    };

    $sendMail = wp_mail(
        get_option('admin_email'),
        sprintf('Kontaktformular von %1$s', $jsonRequest['name']),
        sprintf(
            'Name: %1$s
Email: %2$s
Telefonnummer: %3$s
Nachricht: %4$s
JSON: %5$s',
            $jsonRequest['name'],
            $jsonRequest['email'],
            $jsonRequest['phone'],
            $jsonRequest['message'],
            json_encode($jsonRequest),
        ),
        sprintf('From: %1$s <"%2$s">', $jsonRequest['name'], $jsonRequest['email']),
    );

    if ($sendMail) {
        echo 'success';
        exit();
    }

    echo 'failure';

    exit();
}

此致敬意

编辑1:

我用 https://ddev.readthedocs.io/en/latest/users/debugging-profiling/step-debugging/#visual-studio-code-vs-code-debugging-setup 进行调试,发现函数的参数不正确,所以我用 .headerswp_mailsprintf('From: %1$s', $jsonRequest['email']),

现在我正在收到邮件,但是没有向客户发送任何回复。为什么?

编辑2:

上面的代码适用于 EDIT2 中提到的更改,我不知道的是,浏览器网络选项卡中的响应将为空,直到在 JavaScript 中调用了类似的东西。await response.text()

php wordpress 电子邮件 wp-mail

评论

0赞 ADyson 10/6/2023
你做了什么调试?您是否至少验证了该函数是否已确定执行?您是否也需要调试代码的ajax部分(我们看不到)?PHP 是否设置为将错误和警告记录到文件中?wp_mail
0赞 pgalle 10/6/2023
感谢您的回复,我发现我的调试无论出于何种原因都被静音了。我用 ddev.readthedocs.io/en/latest/users/debugging-profiling/...

答:

0赞 pgalle 10/6/2023 #1

整个工作的 PHP 部分如下所示:

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() {
    $jsonRequest = json_decode(file_get_contents('php://input'), true);
    if (strcmp($jsonRequest['action'], 'contact_form') !== 0) {
        echo 'failure';
        exit(1);
    };

    $sendMail = wp_mail(
        get_option('admin_email'),
        sprintf('Kontaktformular von %1$s', $jsonRequest['name']),
        sprintf(
            'Name: %1$s
Email: %2$s
Telefonnummer: %3$s
Nachricht: %4$s',
            $jsonRequest['name'],
            $jsonRequest['email'],
            $jsonRequest['phone'],
            $jsonRequest['message'],
            // json_encode($jsonRequest),
        ),
        sprintf('From: %1$s', $jsonRequest['email']),
    );

    if ($sendMail) {
        echo 'success';
        exit();
    }

    echo 'failure';

    exit();
}

在 JavaScript 端,调用很重要,否则响应将不会在浏览器网络选项卡中可见。await response.text()

window.addEventListener("load", () => {
  /**
   * @type Array<HTMLFormElement>
   */
  const forms = Array.from(
    document.querySelectorAll(".contact-form")
  );

  forms.forEach((form) => {
    form.addEventListener("submit", async (e) => {
      e.preventDefault();

      const response = await fetch(
        "/wp-admin/admin-ajax.php?action=mail_before_submit",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            action: "contact_form",
            ...Object.fromEntries(new FormData(form)),
          }),
        }
      );

      console.log({ response });
      if (!response.ok) {
        console.error("ERROR");

        return;
      }

      if ((await response.text()) === "success") {
        form.classList.add("success");
      }
    });
  });
});