404页面邮件表单missing_content提示无法显示问题求助
解决404页面邮件表单的missing_content提示不显示问题
我仔细看了你的代码,问题出在判断逻辑的顺序和isset()的使用方式上,导致两个字段都为空时,代码根本没走到触发missing_content提示的分支里。
问题根源分析
当用户提交表单时,哪怕message_human字段是空字符串,isset($_POST['message_human'])依然会返回true(因为表单里存在这个字段,只是值为空),所以代码会直接进入第一个if (isset($human))分支,完全跳过了后面的else if (isset($_POST['submitted']))分支。
而在第一个分支里,你的判断条件if(!$human == 0)存在运算符优先级问题:!$human会先执行,空字符串被转为布尔值false,取反后是true,然后true == 0在PHP中等价于false,所以这个条件不成立,代码直接跳过所有内部判断,没有生成任何提示。
修复方案
调整判断逻辑的顺序,先确认表单已提交,再逐个验证必填字段是否有实际内容,同时修正运算符优先级的问题:
<?php $response = ""; function my_contact_form_generate_response($type, $message){ global $response; if($type == "success") $response = "<p><div class='success' style='margin-right: 10vw;'>{$message}</div></p>"; else $response = "<p><div class='error' style='margin-right: 10vw;'>{$message}</div></p>"; } $not_human = "Are you sure you're not a robot?"; $missing_content = "Please fill in every field."; $message_unsent = "Something went wrong, please try again."; $message_sent = "Thanks for your help, your message has been send."; $name = wp_get_current_user(); $message = isset($_POST['message_text']) ? $_POST['message_text'] : ''; $human = isset($_POST['message_human']) ? $_POST['message_human'] : ''; $to = "fake@mail.com"; $subject = "404 found by: " . $name->user_login; // 先判断表单是否提交 if (isset($_POST['submitted'])) { // 检查必填字段是否为空 if (empty($message) || empty($human)) { my_contact_form_generate_response("error", $missing_content); } else { // 验证人机交互 if($human != $_SESSION['outcome']) { my_contact_form_generate_response("error", $not_human); } else { // 处理邮件发送 $full_message = "link: http://vespa-ciao.nl" . $url . "\n\n" . $message; $sent = wp_mail($to, $subject, strip_tags($full_message)); if($sent) my_contact_form_generate_response("success", $message_sent); else my_contact_form_generate_response("error", $message_unsent); } } } // 生成人机验证的随机数 $number = array( mt_rand(1,5), mt_rand(6,10) ); $outcome = $number[1] - $number[0]; $_SESSION['outcome'] = $outcome; ?>
关键改动说明
- 调整判断顺序:先检查
isset($_POST['submitted'])确认表单已提交,再进行字段验证,确保所有提交场景都能被覆盖。 - 字段初始化优化:用三元运算符简化字段的
isset判断,同时默认赋值为空字符串,避免未定义变量的问题。 - 必填字段验证:直接用
empty()检查message和human是否有实际内容,只要其中一个为空就触发missing_content提示。 - 修正人机验证逻辑:去掉容易混淆的
!$human ==0,直接用$human != $_SESSION['outcome']验证,逻辑更清晰。 - 邮件内容格式修正:把换行符改成
\n\n,确保邮件内容排版正常(原来的代码里直接换行在PHP中会被解析为空格)。
这样修改后,当两个字段都为空时,就能正常触发missing_content提示了。
内容的提问来源于stack exchange,提问作者AA-T
相关产品推荐
相关产品推荐

