Skip to content

Instantly share code, notes, and snippets.

@hattmarris
Last active August 29, 2015 14:13
Show Gist options
  • Save hattmarris/dadcb72ff0b9fd8858e1 to your computer and use it in GitHub Desktop.
Save hattmarris/dadcb72ff0b9fd8858e1 to your computer and use it in GitHub Desktop.
Simple WordPress Contact Form
<?php
if($_POST['submit'] == 'Submit') {
//prevent injection
if (!isset( $_POST['contact_form_nonce'] ) || ! wp_verify_nonce( $_POST['contact_form_nonce'], 'submit_contact_form' ) ) {
print 'Sorry, your nonce did not verify.';
exit;
}
//prevent spam
if(isset($_POST['foo']) && trim($_POST['foo']) != '') {
print 'Sorry, your submission has failed.';
exit;
}
//process form data
else {
$name = $_POST['contact-form-name'];
$email = $_POST['contact-form-email'];
$message = $_POST['contact-form-message'];
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$subject = 'Contact Form Submission';
$headers = 'From: '.$name.' <'.$email.'>' . "\r\n";
$to = get_option('admin_email');
wp_mail( $to, $subject, $message, $headers, $attachments );
echo 'Thank you. Your message has been successfully submitted.';
} else {
echo '<style>.contact-form-input-email label {color: #FF0000; font-weight: bold;} .contact-form-input-email label:before {content: "*";} .contact-form-input-email:after {content: "Please enter a valid email address";}</style>';
}
}
} else {
?>
<form method="post">
<div class="contact-form-input-name">
<label for="contact-form-name">Full Name:</label>
<br>
<input id="contact-form-name" name="contact-form-name" type="text" />
</div>
<div class="contact-form-input-email">
<label for="contact-form-email">Email:</label>
<br>
<input id="contact-form-email" name="contact-form-email" type="text" />
</div>
<div class="contact-form-input-message">
<label for="contact-form-message">Message:</label>
<br>
<textarea rows="4" cols="100" id="contact-form-message" name="contact-form-message"></textarea>
</div>
<br>
<?php wp_nonce_field('submit_contact_form','contact_form_nonce'); ?>
<div id="fooDiv">
<label for="foo">Leave this field blank</label>
<input type="text" name="foo" id="foo">
</div>
<script>
(function () {
var e = document.getElementById("fooDiv");
e.parentNode.removeChild(e);
})();
</script>
<input type="submit" id="submit" name="submit" value="Submit"></input>
</form>
<?php } ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment