WordPress Contact Form 7自定义单选框必填验证需求
Contact Form 7自定义单选短代码添加必填验证
我是WordPress PHP新手,现有一段生成[goldkarat]自定义单选框短代码的Contact Form 7代码,需要给它添加必填验证功能:当使用带星号的必填短代码[goldkarat*]时,若用户未选择任何选项,表单提交时需返回错误提示。
原代码
function add_shortcode_metalspurityradio() { wpcf7_add_shortcode( 'goldkarat', 'metalspurityradio_handler', true ); } add_action( 'wpcf7_init', 'add_shortcode_metalspurityradio' ); function metalspurityradio_handler( $tag ){ $tag = new WPCF7_FormTag( $tag ); $atts = array( 'type' => 'radio', 'name' => $tag->name, 'list' => $tag->name . '-options' ); $input = sprintf( '<input %s />', wpcf7_format_atts( $atts ) ); $datalist = ''; $datalist .= '<div class="goldkaratradio d-flex">'; foreach ( $tag->values as $val ) { list($radiovalue,$imagepath) = explode("!", $val ); $datalist .= sprintf( '<div class="quotetabswrap col-md-1 col-xs-2 p-1"> <label class="quotetabslabel p-1 pb-0 mb-1"> <input type="radio" name="%s" value="%s" class="hideradio" /> <div class="quotetabsshape"> <div id="'.$radiovalue.'" class="quotetabstext">%s</div> </div> </label> </div>', $tag->name, $radiovalue, $radiovalue, $radiovalue ); } $datalist .= '</div>'; return $datalist; }
解决方案(修改后完整代码)
要实现必填验证,需添加后端验证规则,同时给前端输入框增加required属性增强用户体验:
function add_shortcode_metalspurityradio() { // 注册短代码,第三个参数true支持带*的必填版本 wpcf7_add_shortcode( 'goldkarat', 'metalspurityradio_handler', true ); } add_action( 'wpcf7_init', 'add_shortcode_metalspurityradio' ); // 添加自定义验证规则 function goldkarat_required_validation( $result, $tag ) { $tag = new WPCF7_FormTag( $tag ); // 仅处理goldkarat类型的必填短代码 if ( 'goldkarat' === $tag->base && $tag->is_required() ) { $name = $tag->name; $value = isset( $_POST[$name] ) ? trim( $_POST[$name] ) : ''; // 未选择选项则标记验证失败 if ( empty( $value ) ) { $result->invalidate( $tag, wpcf7_get_message( 'invalid_required' ) ); } } return $result; } add_filter( 'wpcf7_validation_filter', 'goldkarat_required_validation', 10, 2 ); function metalspurityradio_handler( $tag ){ $tag = new WPCF7_FormTag( $tag ); // 给必填项的radio输入框添加required属性 $required_attr = $tag->is_required() ? 'required' : ''; $datalist = ''; $datalist .= '<div class="goldkaratradio d-flex">'; foreach ( $tag->values as $val ) { list($radiovalue,$imagepath) = explode("!", $val); $datalist .= sprintf( '<div class="quotetabswrap col-md-1 col-xs-2 p-1"> <label class="quotetabslabel p-1 pb-0 mb-1"> <input type="radio" name="%s" value="%s" class="hideradio" %s /> <div class="quotetabsshape"> <div id="%s" class="quotetabstext">%s</div> </div> </label> </div>', esc_attr($tag->name), esc_attr($radiovalue), $required_attr, esc_attr($radiovalue), esc_html($radiovalue) ); } $datalist .= '</div>'; return $datalist; }
关键修改说明
- 后端验证:通过
wpcf7_validation_filter钩子拦截表单提交,检查必填的goldkarat字段是否有选中值,无则返回CF7默认必填错误提示。 - 前端提示:判断短代码是否为必填项,给对应的radio输入框添加
required属性,触发浏览器原生必填提示。 - 安全优化:使用
esc_attr()和esc_html()对输出的属性、文本进行转义,避免XSS风险。
必填短代码使用示例
[goldkarat* metals-purity "1K" "2K" "3K" "4K" "5K" "6K" "7K" "8K" "9K" ]
内容的提问来源于stack exchange,提问作者Chris k
相关产品推荐
相关产品推荐

