不需要 Wordpress Contact Form 7 收音机

Wordpress Contact Form 7 radio not required

我有一个只有几个字段和一个单选按钮的表单。此单选按钮是一个可选字段。但是,如果我没有 select 单选按钮中的任何选项,我将无法提交表单。

<div class="input-field-outer">
    [text* your-name class:name placeholder "Name or business name*"]
</div>
<div class="input-field-outer">
    [email* email placeholder "Email*"]
</div>
<div class="input-field-outer">
    [text* contact-number id:telno class:hs-phone-number placeholder "Contact number*"]
    <span id="errmsg"></span>
</div>
<div class="input-field-outer">
    <div class="radio-outer">
        [radio customer_type "New Customer" "Old Customer"]
    </div>
</div>

当我将它们中的任何一个设置为默认值时它都会起作用select:

[电台customer_typedefault:1"New Customer""Old Customer"]

关于使用没有默认项的单选按钮的任何想法。

解决方法是使用复选框并添加独占参数。这使您可以在不选择客户类型的情况下提交表单。

[checkbox customer_type exclusive "New Customer" "Old Customer"]

您可以 select 使用选项 select 默认编辑哪个单选按钮 default:1 用于第一个收音机或 default:2 用于第二个收音机,依此类推。

添加选项 default:0 完全符合您的要求。它使所有单选按钮都未selected。

Checkbox exclusive 实际上对我不起作用,因为主题 CSS 不支持它。

无需为主题添加 JS 和 CSS 来支持此功能,我已经通过使用一个 "empty" 字段成功地解决了无线电问题:

[radio choice label_first default:1 "" "Yes" "No"]

之后在 CSS 我添加了:

.wpcf7-list-item.first {
    display: none;
}

这选择了第一个未在前端(和生成的邮件)中显示的选项,并使复选框在验证中实际上不再需要。

要删除对所有单选字段的验证,请将此添加到 functions.php 或任何合适的地方。

remove_filter('wpcf7_validate_radio', 'wpcf7_checkbox_validation_filter', 10);

如果您想对一些 收音机保持所需的验证,请将它们更改为:

[radio fieldName class:required "Yes" "No"]

然后将此代码添加到 functions.php:

remove_filter('wpcf7_validate_radio', 'wpcf7_checkbox_validation_filter', 10);

add_filter('wpcf7_validate_radio', function($result, $tag) {
  if (in_array('class:required', $tag->options)) {
    $result = wpcf7_checkbox_validation_filter($result, $tag);
  }
  return $result;
}, 10, 2);

只需阅读 this 评论,其中写道:

The author of CF7, Takayuki Miyoshi, believes a radio button is a required field by default. And he’s not the only one. This follows W3C’s HTML specifications for radio buttons.

If you need to have no required option you can switch to using a checkbox.

因此,构建变通方案不符合 W3C 的规范,因此可能不是最佳解决方案。