Most websites are typically designed to comply with standard web practices by including a dedicated page where a contact form is located. This provides visitors with an easy way to reach out to the site owner.

In simple terms, a contact form has a set of questions and fields which are filled in by a visitor. The information is usually automatically sent via email to the site administrator or another nominated email account. It is worth noting that this email address isn’t displayed to visitors, so using a contact form typically reduces email spam from bots that harvest naked email addresses on the Internet. Contact forms play a very important role on a website, where they are used for collecting feedback, enquiries and other data from users.

If your website is powered by WordPress, there are numerous plugins that seamlessly integrate a contact form on your website.

In this article, I will provide a list of some free WordPress contact form plugins. I will also discuss why you should consider rolling your own contact form. Then, I will provide you with a short tutorial showing you how to build your own WordPress contact form plugin.

WordPress Contact Form Plugins

Before we get started, we’re going to go over a few of the popular free contact form plugins available in the WordPress Plugin Directory. These are great to use, but even better to learn from when you’re getting started building your own plugins.

Below are some of the most highly rated free contact form plugins for WordPress:

  1. Contact Form 7 – This is the second most popular plugin with over 18 million downloads, it could almost be considered as the de facto contact form plugin for a WordPress website. Contact Form 7 can manage multiple contact forms and you can customize the form and the email contents with simple markup. The form features include Ajax-powered submission, CAPTCHA, Akismet spam filtering and lots more.

  2. Contact Form to Email – This plugin not only creates contact forms and sends the data to a specified email address it also saves the contact form data into a database, providing printable reports and the option to export the selected data to CSV/Excel file.

  3. FormGet Contact Form – An easy online drag and drop contact form builder tool. All you need to do is click on the fields that you want in your form, and within few seconds your contact form is ready.

  4. Bestwebsoft Contact Form – Allows you to implement a feedback form to a web page or a post effortlessly. It is extremely easy, and you won’t require any additional settings, even though there are some available to play with.

Why Roll Your Own Contact Form Plugin?

Becoming a Better Developer

Developing your own WordPress plugin helps you better understand how WordPress works ‘under the hood’ which can help you to become a more experienced web developer. While there are tens of thousands of plugins in the WordPress Plugin Directory to use, being able to modify and extend other plugins is a very useful skill.

Building a Better Form

Many WordPress contact form plugins are bloated. They include many features that you may never use. Heavy usage of JavaScript and CSS files are also common in some of the standard contact form plugins. This increases the number of HTTP requests which adversely affects WordPress performance.

According to Yahoo’s performance rules:

80% of the end-user response time is spent on the front-end. Most of this time is tied up in downloading all the components in the page: images, stylesheets, scripts, Flash, etc. Reducing the number of components in turn reduces the number of HTTP requests required to render the page. This is the key to faster pages.

If you are like me, and you desire a simple contact form plugin that just works, read on. I’ll guide you through the simple process of develop your own plugin so you can kiss goodbye bloated plugins. In this example no extra CSS and JavaScript files are required, the validation done using HTML5.

Contact Form Plugin Development

In five minutes, you will learn how to develop a simple WordPress contact form, that’s a promise!

Ready? Set? Go!

All WordPress pluigns are PHP files, located in the /wp-content/plugins/ directory. In our example, the file will be called sp-form-example.php. I assume you’re comfortable with connecting to your server using FTP/SFTP/SCP or SSH.

If you want to follow along, simply create a file called sp-form-example.php (the final complete example will be available at the end of the article):

<?php
/*
Plugin Name: Example Contact Form Plugin
Plugin URI: http://example.com
Description: Simple non-bloated WordPress Contact Form
Version: 1.0
Author: Agbonghama Collins
Author URI: http://w3guy.com
*/
    //
    // the plugin code will go here..
    //
?>

Next, we add the function html_form_code() that contains the contact form HTML:

function html_form_code() {
    echo '<form action="' . esc_url( $_SERVER['REQUEST_URI'] ) . '" method="post">';
    echo '<p>';
    echo 'Your Name (required) <br />';
    echo '<input type="text" name="cf-name" pattern="[a-zA-Z0-9 ]+" value="' . ( isset( $_POST["cf-name"] ) ? esc_attr( $_POST["cf-name"] ) : '' ) . '" size="40" />';
    echo '</p>';
    echo '<p>';
    echo 'Your Email (required) <br />';
    echo '<input type="email" name="cf-email" value="' . ( isset( $_POST["cf-email"] ) ? esc_attr( $_POST["cf-email"] ) : '' ) . '" size="40" />';
    echo '</p>';
    echo '<p>';
    echo 'Subject (required) <br />';
    echo '<input type="text" name="cf-subject" pattern="[a-zA-Z ]+" value="' . ( isset( $_POST["cf-subject"] ) ? esc_attr( $_POST["cf-subject"] ) : '' ) . '" size="40" />';
    echo '</p>';
    echo '<p>';
    echo 'Your Message (required) <br />';
    echo '<textarea rows="10" cols="35" name="cf-message">' . ( isset( $_POST["cf-message"] ) ? esc_attr( $_POST["cf-message"] ) : '' ) . '</textarea>';
    echo '</p>';
    echo '<p><input type="submit" name="cf-submitted" value="Send"/></p>';
    echo '</form>';
}

Basic validation was added to the form via the pattern input attribute.

The RegEX in the contact form does the following field validation:

  • [a-zA-Z0-9 ]: only letters, spaces and numbers allowed in the name field; special symbols are deemed invalid.

  • [a-zA-Z ]: only letters and spaces are allowed in the subject field.

  • The email form control validates the email field hence there is no need for a pattern attribute.

For more information on how this works, read my article on Client-Side Form Validation with HTML5 to understand how the pattern attribute assists with form validation.

Hurry Up!

Okay, how many minutes do we have left? Four minutes! We still have time to get this over with.

The function deliver_mail() sanitizes the form data and sends the mail to the WordPress administrator’s email address.

function deliver_mail() {

    // if the submit button is clicked, send the email
    if ( isset( $_POST['cf-submitted'] ) ) {

        // 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";

        // If email has been process for sending, display a success message
        if ( wp_mail( $to, $subject, $message, $headers ) ) {
            echo '<div>';
            echo '<p>Thanks for contacting me, expect a response soon.</p>';
            echo '</div>';
        } else {
            echo 'An unexpected error occurred';
        }
    }
}

The sanitation of the form data is done by the following WordPress internal functions:

  • sanitize_text_field(): Sanitize the data from user input.

  • sanitize_email(): Strips out all characters that are not allowable in an email.

  • esc_textarea(): Escape the message text area values.

The code get_option( 'admin_email' ) programmatically retrieves the WordPress administrator’s email address from the database where the email will be delivered to.

Don’t want the contact form to send the mail to admin? Simply set the variable $to to the desired email address.

If the email has successfully been processed without any errors by the function wp_mail() , the text Thanks for contacting me, expect a response soon will be shown, otherwise An unexpected error occurred is displayed.

1 Minute and 30 Seconds Left

The function cf_shortcode() is the callback function that is called when the contact form shortcode [sitepoint_contact_form] is active.

function cf_shortcode() {
    ob_start();
    deliver_mail();
    html_form_code();

    return ob_get_clean();
}

The above functions calls the html_form_code() and deliver_mail() functions to display the contact form HTML form and validate the form data respectively.

Finally, the shortcode [sitepoint_contact_form] is registered to WordPress. So simply add:

add_shortcode( 'sitepoint_contact_form', 'cf_shortcode' );

3, 2, 1… Time’s Up!

Congratulations, we have successfully developed our own WordPress contact form plugin and I have fulfilled my earlier promise.

Now, to use this plugin on your website, simply activate it in under the ‘Plugins’ section of your WordPress dashboard, then create a post or page and then simply add the shortcode where you want the form to appear [sitepoint_contact_form].

If you then preview the page and you should see the contact form displayed as shown below.

WordPress Contact Form Plugin Example

Conclusion

To further understand how the plugin was built and how to implement it on your WordPress site, copy the code below, paste in a file and upload it to your /wp-content/plugins/ directory.

Here’s the entire plugin example:

<?php
/*
Plugin Name: Example Contact Form Plugin
Plugin URI: http://example.com
Description: Simple non-bloated WordPress Contact Form
Version: 1.0
Author: Agbonghama Collins
Author URI: http://w3guy.com
*/

function html_form_code() {
	echo '<form action="' . esc_url( $_SERVER['REQUEST_URI'] ) . '" method="post">';
	echo '<p>';
	echo 'Your Name (required) <br/>';
	echo '<input type="text" name="cf-name" pattern="[a-zA-Z0-9 ]+" value="' . ( isset( $_POST["cf-name"] ) ? esc_attr( $_POST["cf-name"] ) : '' ) . '" size="40" />';
	echo '</p>';
	echo '<p>';
	echo 'Your Email (required) <br/>';
	echo '<input type="email" name="cf-email" value="' . ( isset( $_POST["cf-email"] ) ? esc_attr( $_POST["cf-email"] ) : '' ) . '" size="40" />';
	echo '</p>';
	echo '<p>';
	echo 'Subject (required) <br/>';
	echo '<input type="text" name="cf-subject" pattern="[a-zA-Z ]+" value="' . ( isset( $_POST["cf-subject"] ) ? esc_attr( $_POST["cf-subject"] ) : '' ) . '" size="40" />';
	echo '</p>';
	echo '<p>';
	echo 'Your Message (required) <br/>';
	echo '<textarea rows="10" cols="35" name="cf-message">' . ( isset( $_POST["cf-message"] ) ? esc_attr( $_POST["cf-message"] ) : '' ) . '</textarea>';
	echo '</p>';
	echo '<p><input type="submit" name="cf-submitted" value="Send"></p>';
	echo '</form>';
}

function deliver_mail() {

	// if the submit button is clicked, send the email
	if ( isset( $_POST['cf-submitted'] ) ) {

		// 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";

		// If email has been process for sending, display a success message
		if ( wp_mail( $to, $subject, $message, $headers ) ) {
			echo '<div>';
			echo '<p>Thanks for contacting me, expect a response soon.</p>';
			echo '</div>';
		} else {
			echo 'An unexpected error occurred';
		}
	}
}

function cf_shortcode() {
	ob_start();
	deliver_mail();
	html_form_code();

	return ob_get_clean();
}

add_shortcode( 'sitepoint_contact_form', 'cf_shortcode' );

?>

This is just a simple example. If you’re interested in learning more about plugin development, here is some further recommended reading:

Let me know your thoughts and questions in the comments.

Collins is a web developer and freelance writer from Nigeria studying Computer Science. When not wrangling with code, you can find him writing at his personal web development blog. Follow him on Twitter @w3guy

Get your free chapter of Level Up Your Web Apps with Go

Get a free chapter of Level Up Your Web Apps with Go, plus updates and exclusive offers from SitePoint.


  • http://www.marketingsensus.com/ landi

    Pure and simple.

  • http://www.zemtime.com Ali Sajjad

    much simple way , thanks Collins

  • http://www.wmwebdesign.co.uk/ Keith Davis

    Agree with @Landi – pure and simple.
    Might give this one a try on my local install.

    Any CSS to pretty it up a bit?

    • http://w3guy.com Agbonghama Collins

      Sure you can use CSS to style it.

      • TAnzeela Zafar

        this plugin is not shown in my dashboard once i install it???? can any body tell me the solution

        • http://w3guy.com Agbonghama Collins

          All WordPress plugin doesn’t need to have a dashboard settings page.

        • http://w3guy.com Agbonghama Collins

          Not all plugins are meant to be shown in the dashboard. Re-read the tutorial on how to use it.

  • bhuppi

    an error occured whne sending email

  • natehawkes

    That looks great! This might be stupid, but do you have any idea how to add Akismet into this? I could add it as a separate class, but considering that Akismet pretty much comes bundled with WordPress these days, do you know how I could hoot into it?

    • http://w3guy.com Agbonghama Collins

      Integrating Akismet to this contact form will make this tutorial complicated.

      The contact form created in this tutorial is meant to be simple.

  • http://www.mrsamirwin.co.uk/ Sam Irwin

    Love this, thanks Agbonghama. One question – what would be the best way of grabbing a select tag from the form?

    • http://w3guy.com Agbonghama Collins

      Use jQuery.

      • piyush

        i m admin.. but i m not getting email from the users?
        ” $to = get_option( ‘admin_email’ );”
        how to get mail from a perticular email address?

        thanks..

        hop u reply very soon

        • Keith

          Can this code be adapted to use on a normal html site, not wordpress?
          Thanks

  • Remo

    Great simple contact form – thanks dear

  • Faizyab

    How can I upload image files, which stores on my server and it’s path is send by email?

  • serundeputy

    wp-newbie; what would the URL be to access this form?

    • serundeputy

      ahh; i see it now under 3, 2, 1 … time’s up;

  • Nishant Gupta

    How to access this plugin

  • Nishant Gupta

    where is shortcode of this plugin

    • http://w3guy.com Agbonghama Collins

      The shortcode is [sitepoint_contact_form]

      • Prachi Kaklij

        Sir, if we want to display this form or use this plugin without including any kind of shortcode, then how can we do this?

  • Santosh Jami

    Very nice plugin. Got “An unexpected error occurred”. Need to figure out how to debug this.

    • http://w3guy.com Agbonghama Collins

      The error is returned if wp_mail fail to process the mail.

      It seems you’ve altered the contact form code.

      Ensure you use the code “as is” unless you are a coder and know what you’re doing.

  • Robert

    I created the file but how do I see it under the plugins page? It seems to be missing?

    • http://w3guy.com Agbonghama Collins

      Not every plugin have a settings page and this is no exception.

  • Nimesh

    Really very nice, super… but got the error “An unexpected error occurred” every time I have changed many think like header also tried to putting all the varible value static like name, email, to , header but even get the error…. any idea.

  • http://w3guy.com Agbonghama Collins

    The error is returned if wp_mail fail to process the mail.

    It seems you’ve altered the contact form code.

    Ensure you use the code “as is” unless you are a coder and know what you’re doing.

  • http://w3guy.com Agbonghama Collins

    You can’t send attachment with this contact form.

  • http://w3guy.com Agbonghama Collins

    Ensure the required field is not left empty – name, email, subject, message.

    • bhuppi

      still have the same error

  • Kevin Armstrong

    Thanks for the amazing work.
    How can I add a simple human verification code to it? Can you do it please?

  • http://www.mursaleen.com/ Mohammad Mursaleen

    Thanks Collins! Great tutorial.

  • nik

    i wnat insert my own site contact form than how can i insert plz tell ne i need ur help

  • http://capeholidays.info/ johan horak

    Hi Agbonghama

    Like your sense of humor, while writing ;-)

    I tried to adapt your plugin for my own use but somehow stuffed it up six love.

    I have created a Google sheet not to put rubbish in your comments. You can have a look at it here https://docs.google.com/document/d/1kNpB5wK1tfPIoitp7Rk7MTI8dj7wAaUbcTV0SWo5gow/edit?usp=sharing

    Thanks for sharing and for assisting.

    Johan

  • http://www.themesrefinery.net/ Rehman Ali

    Really nice and helpful code.

  • Jayden Lawson

    Thanks Agbonghama! However – I get 2 emails every time this form is sent. The code is the same as yours – why would this be?

  • Kapil

    Great Work…!!! Sent mail successfully also display message ‘Thanks for contacting me, expect a response soon’ but mail didn’t recieve.

  • Kapil

    Great work…!!!!
    sent Mail successfully as well display message ‘Thanks for contacting me, expect a response soon.’.
    but didn’t receive mail.

  • Atul Sharma

    hey..,i am new in wordpress i want know how can we add options in this

  • http://www.travelpod.com/travel-photo/billieandsherm/3/1223781780/kirkenes-03.jpg/tpod.html Патрик Жданов

    Hello! How would you store this information into the database as well???

  • Arif Phaedra

    Thats great, but i am trying to make plugin in which there is image upload, so how i can upload image and save in my directory. Thanks in advance

  • Arif Phaedra

    Thats great, but i am trying to make plugin in which there is image upload, so how i can upload image and save in my directory. Thanks in advance

  • pabloxime

    Nice job! This tutorial works well. I got it running in 2-3 minutes in a responsive wp theme .
    Can you recommend how reset the form fields after submission?

  • TAnzeela Zafar

    this plugin is not shown in my dashboard once i install it???? can any body tell me the solution

  • odko

    Not Working on Localhost An unexpected error occurred

  • kitty

    thanks dear its really good work… keep it up

  • http://myvivaid.com Robert

    thanks for share this great article. But if I want to add this form into my main page how can I do it?
    What is PHP code to call this form?

  • Mianne Bagger

    Thank you, thank you, thank you for this tutorial! ….I have previously read through about 6 ‘tutorials’ and ‘how-to’s’, and yours is the first that has actually helped me get my first plugin off the ground!! I found the others incredibly confusing (even though I have php/mysql/javascript programming abilities), but yours has enabled me to get a basic version up and running. Perfect!

    One thing that might be worth adding (after I just spent 2hrs fault finding) – I had two empty spaces after the closing ‘?>’ tag that I didn’t know were there. They were causing continuous errors when activating the plugin.

    Thanks again. :)

  • sergio

    Thanks for this article, it is really good in order to start with first plugin, i would like to add two features, I have an idea about how to do it but wanted your opinion:
    – send the data to an external db?
    – show the “thanks” message in a new page?

    Thanks for your help

  • jaya

    thanks it is nice and easy coded plugin , iam using it in wamp and “An unexpected error occurred”, i just want to know weather it will work in wamp or not,plz send me the solution

  • http://webexperts.us Mark Lovett

    NIce job on the tutorial Agbong! I really appreciate the simplicity and your humor as well. Best, Mark http://wordpresstechsupport.biz

  • deepakmalviya

    hi guys i have problem when i submitted form then it shows error:unexpected error occur

  • James

    Really great tutorial Agbonghama! Thank you. I for one would love to see a follow up tutorial adding simple check boxes, and radio buttons. And as some else said, how to clear the form after the submit button is sent. Thanks again!

  • btistaa

    Awesome explanation
    Can u please explain the double and single quotes on this line please t
    echo ”;

  • Ranvir Singh

    Thanks Collins! Great tutorial i use my own business website http://www.rflwebs.com.

  • [James]

    Is it possible to Create a Form that allows users/visitors to Submit actual content such as uploading a document or pdf to me?

  • Nazneen Syed

    amazing…. Thank you :)

  • Nazneen Syed

    Can I ask for your help in making a simple web crawler?

  • Devinder Bawa

    Very nice intro for someone who is looking to make wordpress plugins, even this small piece of code explained a lot. Thanks guy!

  • Devinder Bawa

    Very nice intro for someone who is looking to make wordpress plugins, even this small piece of code explained a lot. Thanks guy!

  • Donna

    The following code is what sets where the form is emailed to
    $to = get_option( ‘admin_email’ );

    You could try manually adding your email address by changing it to
    $to = “your@email.here”;

    or to troubleshoot what is been used add this (but delete again after) under the form
    echo get_option( ‘admin_email’ );

    Hope that helps

  • DJEB

    Unfortunately, when I put in the shortcode, it just displays the shortcode. I don’t get the form on my page.

  • DJEB

    Same here.

  • Nykeri Grant

    Unfortunately this doesn’t work for me, it only shows the shortcode on display and not the form

Related books & courses
Introduction to Wordpress

Available on SitePoint Premium. Check it out now!