wpcf7_before_send_mail中的自定义错误消息

时间:2018-01-12 18:46:56

标签: wordpress api contact-form-7

美好的一天!

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

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

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

同一条船上的其他人?

3 个答案:

答案 0 :(得分:0)

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

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必须是此表单现有字段的名称。

答案 1 :(得分:0)

我不确定在您提出问题时是否可能,但是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");
  }
}

答案 2 :(得分:0)

基于路易丝·菲利普的回答,我用这段代码解决了这个问题,因为$ 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,因此您可以将红色边框作为预定义的错误消息。