There are a couple of problems that may lead to failure of your script.
First, you have a check for $mailSent
at the top so you can redirect. However, at that point, it is undefined. It would be less likely to be a problem if you move it to where you check it at the end and set an error. In fact, I would move all of that outside your if (!$suspect && !$missing && !$errors) {
check.
And that brings up another similar problem. Where does $suspect
come from? This appears to be undefined as well. I’d take that out if it isn’t supposed to be there.
Here are those changes:
$errors = array();
$missing = array();
if (isset($_POST['send'])) {
$to = '[email protected]';
$subject="Form";
$expected = array('name', 'email', 'pick_up_adress', 'drop_off_adress', 'phone', 'pick_date', 'pick_time', 'type');
$required = array('name', 'email', 'pick_up_adress', 'drop_off_adress', 'phone', 'pick_date', 'pick_time', 'type');
$headers = "From: Metro<[email protected]>\r\n";
$headers .= 'Content-Type: text/plain; charset=utf-8';
}
// Array proccesing
$mailSent = false;
if (!$missing && !$errors) {
$message="";
foreach($expected as $item) {
if (isset(${$item}) && !empty(${$item})) {
$val = ${$item};
} else {
$val="Not selected";
}
if (is_array($val)) {
$val = implode(', ', $val);
}
$item = str_replace(array('_', '-'), ' ', $item);
$message .= ucfirst($item).": $val\r\n\r\n";
}
$message = wordwrap($message, 70);
// simple php doc $mailSent = mail($to, $subject, $message, $headers);
$mailSent = wp_mail($to, $subject, $message, $headers);
}
if ( $mailSent ) {
header('Location: after_form.php');
exit;
} else {
$errors['mailfail'] = true;
}
Lastly, I would be inclined to put this in an action hook rather than in a template. It can certainly work in a template, so that’s up to you, but I think a hooked action such as init
would be more portable.