I have created a WP template and added to it a form. Below the form I have added the wp_mail() function to send the data the user has input to their email.
Now, I'm getting notices that:
Notice: Undefined index: name in mypath.
Any help how to resolve this would be most welcome.
Edit 1: to get the notice I had to remove the if statement.
Edit 2: this is literally all the code I have concerning the form. Am I missing something? Do I need to add add_action()
somewhere or something like that?
The code:
<form id="form" method="post" action="">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
</br>
<label for="surname">Surname:</label>
<input type="text" id="surname" name="surname">
</br>
<label for="email">Email:</label>
<input type="email" id="email" name="email">
</br>
<label for="tel">Phone number:</label>
<input type="tel" id="tel" name="tel">
</br>
<input type="submit" value="Submit" name="submit">
</form>
<?php
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$to = $_POST[$email]; //sendto@example.com
$subject = 'Reservation';
$body = 'Name: ' . $name . '\r\n' .
'Surname: ' . $surname . '\r\n' .
'Email ' . $email . '\r\n' .
'Phone number: ' . $tel . '\r\n';
wp_mail( $to, $subject, $body );
echo "Sent!";
}
?>
The anwser
Edit 3: just to make it clear the solution was $to = $_POST['email']; //sendto@example.com
so ['email']
not [$email]
.
The if statement is a sensible check - you don't want that code running until the $_POST variable has some values in it.
But, none of your form elements have names! eg this
<input type="tel" id="tel">
should be
<input type="tel" id="tel" name="tel">
Without that, you're not going to get very much.
PS Checkout PHP heredoc. That code at the end could be much more neatly written as:
$body = <<< EOT
Name: $name
Surname: $surname
Email: $email
Phone number: $tel
EOT;