【问题标题】:Custom error message within wpcf7_before_send_mailwpcf7_before_send_mail 中的自定义错误消息
【发布时间】:2020-02-25 20:22:21
【问题描述】:

美好的一天!

我正在使用 Contact Form 7 及其 wpcf7_before_send_mail 操作在发送电子邮件之前与 API 进行交互。如果 API 返回错误,我希望能够抓取该错误,将其显示为错误并阻止提交表单。

我似乎无法在网上任何地方找到我要找的东西。我能做的最好的就是使用mail_sent_ok 消息字符串并在其中显示错误(这显然不是解决方案)。

基本上,最终的解决方案是强制表单提交失败。

还有其他人在同一条船上吗?

【问题讨论】:

    标签: wordpress api contact-form-7


    【解决方案1】:

    我不确定在您提出问题时是否可行,但 wpcf7_before_send_mail 挂钩有一个中止标志,您只需设置该标志即可避免发送邮件。

    例如在伪 PHP 中

    add_action('wpcf7_before_send_mail', 'your_function', 10, 3);
    function your_function($form, &$abort, $object){
      $error = 1;
      if($error != 0) {
          $abort = true;
          $object->set_response("An error happened");
      }
    }
    

    【讨论】:

    • +1 用于中止参数。我发布了另一个答案,因为对我来说 '$object' 参数始终为空。你把我带到了正确的方向
    【解决方案2】:

    您可以使用此过滤器进行自定义验证:

    add_filter("wpcf7_validate", function ($result, $tags) {
    
        $valid = FALSE; // here you can do your API call to calculate the validation
    
        if (!$valid) {
    
            $result->offsetSet(
                  "reason"
                , ["your-name" => "error message for this field"]
            );
    
        }
    
    
        return $result;
    
    }, 10, 2);
    

    your-name 必须是此表单的现有字段的名称。

    【讨论】:

      【解决方案3】:

      根据 Louise-Philippe 的回答,我用这段代码解决了问题,因为 $object 参数碰巧总是为空:

      add_action('wpcf7_before_send_mail', 'your_function', 10, 3);
      function your_function($form, &$abort, $object){
        $error = 1;
        if($error != 0) {
            $abort = true;
            $msgs = $form->prop('messages');
            $msgs['mail_sent_ng'] = "An error happened"; //<- your custom error message
            $form->set_properties(array('messages' => $msgs));
        }
      }
      

      注意:不是mail_sent_ok,而是mail_sent_ng,因此您可以将红色边框作为预定义的错误消息。

      【讨论】:

        猜你喜欢
        • 2018-08-12
        • 2014-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-03
        • 1970-01-01
        • 2015-09-21
        相关资源
        最近更新 更多