Creating a Custom Contact Form Shortcode
Basic Approach
We'll create a shortcode that displays a contact form and handles form submissions. The form will include basic fields like name, email, and message.
First, let's register the shortcode:
function custom_contact_form_shortcode() {
ob_start();
display_contact_form();
return ob_get_clean();
}
add_shortcode('contact_form', 'custom_contact_form_shortcode');
Here's the form display function with basic styling:
function display_contact_form() {
$form = '
<form id="custom-contact-form" method="post">
<p>
<label for="name">Name:</label>
<input type="text" name="name" required>
</p>
<p>
<label for="email">Email:</label>
<input type="email" name="email" required>
</p>
<p>
<label for="message">Message:</label>
<textarea name="message" required></textarea>
</p>
<input type="hidden" name="contact_form_submitted" value="1">
' . wp_nonce_field('contact_form_submit', 'contact_nonce', true, false) . '
<button type="submit">Send Message</button>
</form>';
echo $form;
}
Form submission handler with security measures:
function handle_contact_form_submission() {
if (!isset($_POST['contact_form_submitted'])) return;
// Verify nonce
if (!wp_verify_nonce($_POST['contact_nonce'], 'contact_form_submit')) {
wp_die('Security check failed');
}
// Sanitize inputs
$name = sanitize_text_field($_POST['name']);
$email = sanitize_email($_POST['email']);
$message = sanitize_textarea_field($_POST['message']);
// Validate email
if (!is_email($email)) {
wp_die('Invalid email address');
}
// Prepare email content
$to = get_option('admin_email');
$subject = 'New Contact Form Submission';
$body = "Name: $name\n";
$body .= "Email: $email\n\n";
$body .= "Message:\n$message";
// Send email
wp_mail($to, $subject, $body);
}
add_action('init', 'handle_contact_form_submission');
Usage
Add this shortcode to any post or page:
[contact_form]
Security Considerations
- Always use nonce verification
- Sanitize all user inputs
- Validate email addresses
- Consider adding CAPTCHA
- Implement rate limiting
- Use SSL if collecting sensitive data
Best Practices
- Add success/error messages
- Include form validation
- Style the form to match your theme
- Add spam protection
- Log form submissions
- Consider using AJAX for submission
Common Pitfalls
- Not sanitizing inputs
- Forgetting nonce verification
- Missing error handling
- Not styling the form
- Inadequate spam protection
Plugin Alternatives
If you need more features, consider these plugins:
-
Contact Form 7
-
WPForms Lite
-
Ninja Forms
Enhancement Options
- Add AJAX submission
- Include file uploads
- Add custom validation
- Create success/error messages
- Style with CSS
- Add anti-spam measures
- Implement email templates
Remember to test thoroughly in different browsers and devices before deploying to production.