Build your own WordPress contact form in 3 steps

1. contact-form.php, create this file and put it in your theme’s root folder. This is the actual html form you will see on a browser. For functionality demonstration purpose, it’s a very simple contact form with no css decoration.

<?php
$requestUri 			= esc_url( $_SERVER['REQUEST_URI'] );
$cfName 				= isset($_POST['cf-name']) ? esc_attr($_POST['cf-name']) : '';
$cfEmail 				= isset($_POST['cf-email']) ? esc_attr($_POST['cf-email']) : '';
$cfSubject 				= isset($_POST['cf-subject']) ? esc_attr($_POST['cf-subject']) : '';
$cfMessage 				= isset($_POST["cf-message"]) ? esc_attr($_POST["cf-message"]) : '';
?>
<form action="<?php echo $requestUri; ?>" method="post">
	<input type="text" placeholder="Your Name" name="cf-name" value="<?php echo $cfName; ?>" size="40" />
	<input type="email" placeholder="Your Email" name="cf-email" value="<?php echo $cfEmail; ?>" size="40" />
	<input type="text" placeholder="Subject" name="cf-subject" value="<?php echo $cfSubject; ?>" size="40" />
	<textarea name="cf-message" placeholder="Message" rows="5" cols="5" id="Message"><?php echo $cfMessage; ?></textarea>
	<input type="submit" name="cf-submitted" value="Submit"></p>
</form>

2. Add the following to the functions.php in your theme’s root folder. You can append it at the end of functions.php. It registers my_contact_form as the shortcode for pulling the contact form.

function sendContactMail() {
	// sanitize form values
	$name    = sanitize_text_field( $_POST["cf-name"] );
	$email   = sanitize_email( $_POST["cf-email"] );
	$subject = sanitize_text_field( $_POST["cf-subject"] );
	$message = esc_textarea( $_POST["cf-message"] );

	// get the blog administrator's email address
	$to = get_option( 'admin_email' );
	$headers = "From: $name <$email>" . "\r\n";

	// Send the email
	if ( wp_mail( $to, $subject, $message, $headers ) ) {
		echo "Thank you for the message!";
	} else {
		echo "Opps, something went wrong!";
	}
}
function processContactForm() {
	ob_start(); //Turn on output buffering
	if ( isset( $_POST['cf-submitted'] ) ) {
		sendContactMail();
	}
	require( get_template_directory() . '/contact-form.php' );
	return ob_get_clean(); // Get current buffer contents and delete current output buffer
}

add_shortcode( 'my_contact_form', 'processContactForm' );

3. To use the contact form, just add the shortcode in a wordpress page or post.

[my_contact_form]

Search within Codexpedia

Custom Search

Search the entire web

Custom Search