This content originally appeared on DEV Community and was authored by danielfilemon
Today I’d like to share how I built a simple contact form plugin for WordPress from scratch. This is a perfect step-by-step guide for anyone who wants to get started developing plugins and understand how the magic behind WordPress really works.
This project is designed both for those who want to learn and for those who want to customize their own websites.
What will we build?
A simple contact form plugin
Fields: name, email, message
Sends the message directly to the WordPress site administrator’s email
Easy to install and activate
You can place the form anywhere using a shortcode
Plugin structure
The project structure looks like this:
my-contact-form-plugin/
├── my-contact-form-plugin.php
└── readme.md
Plugin code
Inside my-contact-form-plugin.php, add:
<?php
/*
Plugin Name: My Contact Form
Description: A simple contact form plugin with shortcode
Version: 1.0
Author: Your Name
*/
// Prevent direct access
if ( ! defined( ‘ABSPATH’ ) ) exit;
/**
- Render the form */ function mcf_render_form() { ob_start(); ?> Name: Email: Message: Send <?php return ob_get_clean(); }
/**
-
Handle the form submission
*/
function mcf_handle_post() {
if ( isset($_POST[‘mcf_submit’]) ) {
$name = sanitize_text_field($_POST[‘mcf_name’]);
$email = sanitize_email($_POST[‘mcf_email’]);
$message = sanitize_textarea_field($_POST[‘mcf_message’]);$to = get_option('admin_email'); $subject = "New contact message from $name"; $body = "Name: $name\nEmail: $email\nMessage:\n$message"; $headers = ["From: $name <$email>"]; wp_mail($to, $subject, $body, $headers); // Simple confirmation add_action('wp_footer', function() { echo "<script>alert('Message sent successfully!');</script>"; });
}
}
add_action(‘init’, ‘mcf_handle_post’);
// Register the shortcode
add_shortcode(‘my_contact_form’, ‘mcf_render_form’);
How to install
1⃣ Upload the plugin folder to wp-content/plugins/
2⃣ Activate it from the WordPress dashboard
3⃣ In any page or post, insert this shortcode:
plaintext
Copiar
Editar
[my_contact_form]
Done! The form will be working for your visitors.
How could it be improved?
This is a basic starter plugin, but you can expand it:
Add prettier styles with CSS
Improve validation (with regex, for example)
Add anti-spam protection (like Google reCAPTCHA)
Save messages to the WordPress database
Display submitted messages in the WordPress admin panel
Code on GitHub
If you want to check the repository, contribute, or make suggestions:
[danielfilemon]
Conclusion
Building plugins for WordPress may sound intimidating, but starting with something small — like a contact form — is an amazing way to understand the structure and the connection between WordPress and PHP.
I hope this tutorial helps you take your first steps! If you’d like to share ideas or collaborate, feel free to reach out here or on GitHub.
This content originally appeared on DEV Community and was authored by danielfilemon