Dec 09 2009
If you’ve been using Wordpress for a while or even if you’ve just done a bit of research you know there are a few excellent contact form plugins available. Since this is the case you may wonder why’d you’d bother creating your own contact form. Why I created mine was to prevent updates from degrading my custom CSS for myself and my clients.
To create a custom form for yourself begin by adding a new function to your functions.php file to print, validate and send emails. Start at the end of your functions.php before the final ?> closing tag with code such as the below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | < ?php
// . . .everything above our new function
// Create a new function to handle the entire contact form
function my_awesome_cf () { ?>
<div class="div4_awesome_cf">
<form action="<?php the_permalink(); ?>" name="my_awesome_cf" class="my_awesome_cf" id="my_awesome_cf" method="post" >
<div class="awesomecf_input_div"><label for="sender_name" class="awesomecf_label required">name </label>
<input type="text" name="sender_name" value="<?php echo $sender_name; ?/>" id="sender_name" class="sender_name awesomecf_input" size="38" tabindex="1" /><span id="name_error" class="awesomecf_error">< ?php echo $bad_sender_name; ?></span></div>
<div class="awesomecf_input_div"><label for="sender_email" class="awesomecf_label required">e-mail </label>
<input type="text" name="sender_email" value="<?php echo $sender_email; ?/>" id="sender_email" class="sender_email awesomecf_input" size="38" tabindex="2" /><span id="email_error" class="awesomecf_error">< ?php echo $bad_sender_email; ?></span></div>
<div class="awesomecf_input_div"><label for="sender_subject" class="awesomecf_label">subject </label>
<input type="text" name="sender_subject" value="<?php echo $sender_subj; ?/>" id="sender_subject" class="sender_subject awesomecf_input" size="38" tabindex="3" /><span id="subj_error" class="awesomecf_error">< ?php echo $bad_sender_subj; ?></span></div>
<div class="awesomecf_input_div sender_msg_div"><label for="sender_message" class="awesomecf_label required">message </label>
<textarea name="sender_message" id="sender_message" class="sender_message awesomecf_textarea" cols="50" rows="8" tabindex="5">< ?php echo $sender_msg; ?></textarea><span id="msg_error" class="awesomecf_error"></span></div>
<div class="awesomecf_input_div">
<input type="submit" name="send_email" value="send" class="submit_awesomecf" tabindex="6" /></div>
</form>
</div>
< ?php
} //END Awesome Contact Form
//close php for entire file
?> |
So far all this function does is output an html form that will literally do nothing. But it’s worth noting a few points about this form as I will be using them later. Each input has a value equal to a php variable. This variable will be empty the first time the page is loaded and we will set it to empty in the event an email sends correctly. If an email fails to send for some reason then the form will be reloaded with whatever information the user tried to send. Each input also has an error span that will advise the user where they’ve made an error in the event their email fails to send. You will also note that a field for the recipient email address has been omitted. I plan to code that directly into php in a later step.
If you’re like me then seeing this in action will help you understand what we’re doing more than anything I can say. I recommend cutting and pasting the above code into your functions.php file. Then head over to your page.php and add the following code right below ‘the_content()’ template tag.
1 2 3 4 5 | < ?php the_content(); ?> < ?php // get post title for php $title = $post->post_title; if (function_exists(my_awesome_cf') && $title == "Contact") {my_awesome_cf();} ?> |
In this bit of code I get the title of the post. . .or page and assign it to the variable $title. Then I have php check that two conditions are true. Does the function “my_awesome_cf” exist and is the current page the “Contact” page. Since you’re awesome both are true and the contact form will be loaded on the contact page only. You can now go back to managing pages in Wordpress as normal and never have to look at page.php again. From now on we’ll modify the form in the functions.php.
At this point you should have a contact form on your contact page that you can fill out and submit but nothing much happens. Let’s add the php that will check the submitted values and send or reject an email. All of the following code goes above the form html and before the “?>” close of php like so.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | function jk_contact_form () { if (isset($_POST['send_email'])) { //If the submit button has been pressed process and send the e-mail otherwise the entire section is skipped // Gather Form Data into variables for validation and email, set recipient email $recipient = "yourname@yourdomain.com"; $sender_name = ($_POST['sender_name']); $sender_email = $_POST['sender_email']; $sender_subj = $_POST['sender_subject']; $sender_msg = $_POST['sender_message']; // Use a regular expression to validate the sender email and set a variable to true if it passes and false if it fails if(preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $sender_email)) { $email_bool = "true"; } else { $email_bool = "false"; } // Use a regular expression to check the sender name had at least 2 letters and no numbers if(preg_match("/^[a-z]{2,}[^0-9]{0,}$/i", $sender_name)) { $sender_bool = "true"; } else { $sender_bool = "false"; } // Use a regular expression to check sender subject Making Sure it contains at least 3 alphanum characters if(preg_match("/^[a-z0-9]{3,}/i", $sender_subj)) { $subj_bool = "true"; } else { $subj_bool = "false"; } // Put the bools into an array so you can check it all at once $bool_array = array($email_bool, $sender_bool, $subj_bool); if (!in_array("false", $bool_array)) { //if false is not in the array and therefore all values are true // Construct email message from variables $msg = "Message from: $sender_name\n\n" . stripslashes($sender_msg); // Use sender's name and email in the from field $headers = 'From: ' . $sender_name . '< ' . $sender_email . '>'; if (mail($recipient, $sender_subj, $msg, $headers)) { echo ' <p style="color:red;">Your message has been sent. '; //set all variables to empty to present the user with a blank form $sender_name = ""; $sender_email = ""; $sender_subj = ""; $sender_msg = ""; } else { echo ' Message failed to send. '; } } else { //at least one false has been returned so make some error messages if ($email_bool == "false") { $bad_sender_email = "Please enter a correct email."; } if ($sender_bool == "false") { $bad_sender_name = "Please enter your name."; } if ($subj_bool == "false") { $bad_sender_subj = "Please enter your subject."; } } } //END POST ?> </p> |
The first time your contact page loads no one has pressed the send button so this entire bit of code is skipped and an empty contact form is printed to the browser. When a user enters some info into the fields, or not, and presses the send button the page loads itself.
This time the send button has been pressed so “if (isset($_POST['send_email']))” is true and this bit of code runs. It confirms the sender name, email and subject fields have values and that they follow a few simple rules. If they do the email sends and the form values are set back to empty. The user gets a message that that their email has been sent and is presented with an empty form to send a second email if they desire. Otherwise they’ve submitted some incorrect info so the form reloads with what they tried to email and error messages to indicate what fields they’ve filled out incorrectly.
Some divs and a few classes and ids allow you to create a form with unique CSS that won’t be altered in the event of unknown changes by a third party. Burying your email address in PHP keeps it safe from prying eyes. Maybe add a little JavaScript to encourage the user to enter valid information before sending an email. All that and you have an awesome contact form you built yourself.