π Introduction
Hey everyone! π
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. π
Top comments (0)