Table of Contents
Key Takeaways
WordPress Contact Form Plugins
Why Roll Your Own Contact Form Plugin?
Becoming a Better Developer
Building a Better Form
Contact Form Plugin Development
Hurry Up!
1 Minute and 30 Seconds Left
3, 2, 1… Time’s Up!
Conclusion
Frequently Asked Questions (FAQs) about Building Your Own WordPress Contact Form Plugin
What are the benefits of creating my own WordPress contact form plugin?
Do I need coding skills to create a WordPress contact form plugin?
How can I ensure the security of my custom WordPress contact form?
Can I add custom fields to my WordPress contact form?
How can I style my WordPress contact form to match my website’s design?
How do I handle the data submitted through my WordPress contact form?
Can I create a multi-step WordPress contact form?
How can I add a CAPTCHA to my WordPress contact form?
Can I create a responsive WordPress contact form?
How can I troubleshoot issues with my WordPress contact form?
Home CMS Tutorial WordPress Build Your Own WordPress Contact Form Plugin in 5 Minutes

Build Your Own WordPress Contact Form Plugin in 5 Minutes

Feb 19, 2025 am 08:36 AM

Build Your Own WordPress Contact Form Plugin in 5 Minutes

Key Takeaways

  • Developing your own WordPress contact form plugin can help you better understand how WordPress works, improve your web development skills, and create a form that is tailored to your specific needs without unnecessary features.
  • The article provides a step-by-step guide on how to create a simple, non-bloated contact form plugin for WordPress, including how to write the PHP code, add basic validation to the form, and send the form data to the site administrator’s email address.
  • The resulting contact form plugin can be easily integrated into any WordPress website by activating it in the ‘Plugins’ section of the WordPress dashboard and adding the provided shortcode to a post or page.
  • The article also discusses some popular free contact form plugins available in the WordPress Plugin Directory, such as Contact Form 7, Contact Form to Email, FormGet Contact Form, and Bestwebsoft Contact Form.

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):

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

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

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

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.

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

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.

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

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:

<span>function deliver_mail() {
</span>
    <span>// if the submit button is clicked, send the email
</span>    <span>if ( isset( $_POST['cf-submitted'] ) ) {
</span>
        <span>// sanitize form values
</span>        <span>$name    = sanitize_text_field( $_POST["cf-name"] );
</span>        <span>$email   = sanitize_email( $_POST["cf-email"] );
</span>        <span>$subject = sanitize_text_field( $_POST["cf-subject"] );
</span>        <span>$message = esc_textarea( $_POST["cf-message"] );
</span>
        <span>// get the blog administrator's email address
</span>        <span>$to = get_option( 'admin_email' );
</span>
        <span>$headers = "From: <span><span>$name</span> <<span>$email</span>>"</span> . "\r\n";
</span>
        <span>// If email has been process for sending, display a success message
</span>        <span>if ( wp_mail( $to, $subject, $message, $headers ) ) {
</span>            <span>echo '<div>';
</span>            <span>echo '<p>Thanks for contacting me, expect a response soon.</p>';
</span>            <span>echo '</div>';
</span>        <span>} else {
</span>            <span>echo 'An unexpected error occurred';
</span>        <span>}
</span>    <span>}
</span><span>}</span>
Copy after login

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.

Build Your Own WordPress Contact Form Plugin in 5 Minutes

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:

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

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

  • A Simple WordPress Administration Plugin (Tutorial)
  • A WordPress Widget Plugin (Tutorial)
  • The Official WordPress Codex Plugin Developer Documentation
  • The SitePoint PHP Channel

Let me know your thoughts and questions in the comments.

Frequently Asked Questions (FAQs) about Building Your Own WordPress Contact Form Plugin

What are the benefits of creating my own WordPress contact form plugin?

Creating your own WordPress contact form plugin gives you full control over the form’s design, functionality, and data handling. You can customize the form to match your website’s aesthetics, add unique fields that cater to your specific needs, and manage the data collected in a way that suits your business operations. Additionally, it eliminates the need for third-party plugins, which can sometimes slow down your website or pose security risks.

Do I need coding skills to create a WordPress contact form plugin?

Yes, basic knowledge of PHP, HTML, and CSS is required to create a WordPress contact form plugin. However, the process is simplified in our guide, making it accessible even for beginners. If you’re not comfortable with coding, there are numerous WordPress form builder plugins available that offer a more user-friendly, drag-and-drop interface.

How can I ensure the security of my custom WordPress contact form?

To ensure the security of your custom WordPress contact form, you should implement measures such as data validation and sanitization, use of nonces for form submission, and protection against spam using CAPTCHA or similar techniques. Regular updates and monitoring are also crucial to maintain the form’s security.

Can I add custom fields to my WordPress contact form?

Yes, one of the advantages of creating your own WordPress contact form is the ability to add custom fields. This can range from simple text inputs to more complex fields like file uploads, date pickers, or even custom dropdowns. The process involves modifying the form’s HTML and handling the data appropriately in your PHP code.

How can I style my WordPress contact form to match my website’s design?

Styling your WordPress contact form to match your website’s design can be achieved using CSS. You can add custom classes to your form elements and define the styles in your theme’s CSS file or a custom CSS plugin. This allows you to control the form’s colors, fonts, layout, and more.

How do I handle the data submitted through my WordPress contact form?

The data submitted through your WordPress contact form can be handled in various ways depending on your needs. You can send the data to an email address, store it in your WordPress database, or even integrate with third-party services like CRM systems or email marketing platforms. This requires additional PHP coding to process the form submission.

Can I create a multi-step WordPress contact form?

Yes, creating a multi-step WordPress contact form is possible but requires more advanced coding. This involves creating multiple form pages and managing the data between steps using sessions or hidden fields. Multi-step forms can improve user experience by breaking down long forms into manageable sections.

How can I add a CAPTCHA to my WordPress contact form?

Adding a CAPTCHA to your WordPress contact form involves integrating with a CAPTCHA service like Google reCAPTCHA. This requires obtaining API keys from the service and adding the necessary HTML and PHP code to your form. CAPTCHA helps protect your form from spam and automated submissions.

Can I create a responsive WordPress contact form?

Yes, creating a responsive WordPress contact form involves using responsive CSS techniques to ensure the form looks good and functions well on all device sizes. This includes setting appropriate widths, margins, and padding for form elements and using media queries to adjust styles for different screen sizes.

How can I troubleshoot issues with my WordPress contact form?

Troubleshooting issues with your WordPress contact form involves identifying the problem, checking your code for errors, and testing the form under different conditions. Common issues include form not sending emails, form not displaying correctly, or form submissions not being saved. If you’re unable to resolve the issue, consider seeking help from the WordPress community or a professional developer.

The above is the detailed content of Build Your Own WordPress Contact Form Plugin in 5 Minutes. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is WordPress easy for beginners? Is WordPress easy for beginners? Apr 03, 2025 am 12:02 AM

WordPress is easy for beginners to get started. 1. After logging into the background, the user interface is intuitive and the simple dashboard provides all the necessary function links. 2. Basic operations include creating and editing content. The WYSIWYG editor simplifies content creation. 3. Beginners can expand website functions through plug-ins and themes, and the learning curve exists but can be mastered through practice.

How To Begin A WordPress Blog: A Step-By-Step Guide For Beginners How To Begin A WordPress Blog: A Step-By-Step Guide For Beginners Apr 17, 2025 am 08:25 AM

Blogs are the ideal platform for people to express their opinions, opinions and opinions online. Many newbies are eager to build their own website but are hesitant to worry about technical barriers or cost issues. However, as the platform continues to evolve to meet the capabilities and needs of beginners, it is now starting to become easier than ever. This article will guide you step by step how to build a WordPress blog, from theme selection to using plugins to improve security and performance, helping you create your own website easily. Choose a blog topic and direction Before purchasing a domain name or registering a host, it is best to identify the topics you plan to cover. Personal websites can revolve around travel, cooking, product reviews, music or any hobby that sparks your interests. Focusing on areas you are truly interested in can encourage continuous writing

How to display child categories on archive page of parent categories How to display child categories on archive page of parent categories Apr 19, 2025 pm 11:54 PM

Do you want to know how to display child categories on the parent category archive page? When you customize a classification archive page, you may need to do this to make it more useful to your visitors. In this article, we will show you how to easily display child categories on the parent category archive page. Why do subcategories appear on parent category archive page? By displaying all child categories on the parent category archive page, you can make them less generic and more useful to visitors. For example, if you run a WordPress blog about books and have a taxonomy called "Theme", you can add sub-taxonomy such as "novel", "non-fiction" so that your readers can

How to get logged in user information in WordPress for personalized results How to get logged in user information in WordPress for personalized results Apr 19, 2025 pm 11:57 PM

Recently, we showed you how to create a personalized experience for users by allowing users to save their favorite posts in a personalized library. You can take personalized results to another level by using their names in some places (i.e., welcome screens). Fortunately, WordPress makes it very easy to get information about logged in users. In this article, we will show you how to retrieve information related to the currently logged in user. We will use the get_currentuserinfo();  function. This can be used anywhere in the theme (header, footer, sidebar, page template, etc.). In order for it to work, the user must be logged in. So we need to use

How to sort posts by post expiration date in WordPress How to sort posts by post expiration date in WordPress Apr 19, 2025 pm 11:48 PM

In the past, we have shared how to use the PostExpirator plugin to expire posts in WordPress. Well, when creating the activity list website, we found this plugin to be very useful. We can easily delete expired activity lists. Secondly, thanks to this plugin, it is also very easy to sort posts by post expiration date. In this article, we will show you how to sort posts by post expiration date in WordPress. Updated code to reflect changes in the plugin to change the custom field name. Thanks Tajim for letting us know in the comments. In our specific project, we use events as custom post types. Now

How to display query count and page loading time in WordPress How to display query count and page loading time in WordPress Apr 19, 2025 pm 11:51 PM

One of our users asked other websites how to display the number of queries and page loading time in the footer. You often see this in the footer of your website, and it may display something like: "64 queries in 1.248 seconds". In this article, we will show you how to display the number of queries and page loading time in WordPress. Just paste the following code anywhere you like in the theme file (e.g. footer.php). queriesin

What is the WordPress good for? What is the WordPress good for? Apr 07, 2025 am 12:06 AM

WordPressisgoodforvirtuallyanywebprojectduetoitsversatilityasaCMS.Itexcelsin:1)user-friendliness,allowingeasywebsitesetup;2)flexibilityandcustomizationwithnumerousthemesandplugins;3)SEOoptimization;and4)strongcommunitysupport,thoughusersmustmanageper

Can I learn WordPress in 3 days? Can I learn WordPress in 3 days? Apr 09, 2025 am 12:16 AM

Can learn WordPress within three days. 1. Master basic knowledge, such as themes, plug-ins, etc. 2. Understand the core functions, including installation and working principles. 3. Learn basic and advanced usage through examples. 4. Understand debugging techniques and performance optimization suggestions.

See all articles