Launch offer
Business website $150 USD Custom plugin $200 USD Ready in 5 days
Get a quote
Contact Form 7

Contact Form 7 Complete Tutorial (100 Topics with Guides & Addon Development)

Complete Contact Form 7 tutorial covering form-tags, mail, validation, spam protection, integrations, developer hooks, and a final custom CF7 addon project.

This complete Contact Form 7 tutorial covers 100 topics — from form-tags and mail templates to validation, spam protection, integrations, developer hooks, and shipping a custom CF7 addon.

Course roadmap

1. Introduction to Contact Form 7

Contact Form 7 (CF7) is a free WordPress form plugin focused on flexible markup, mail templates, and developer-friendly hooks. This series covers tags, mail, validation, spam, integrations, and a final custom addon project.

  1. Install CF7 and create a contact form.
  2. Learn mail tags and validation.
  3. Extend with hooks and ship a custom addon.

Learning path

Install → form tags + mail
Messages + validation + AJAX
Hooks → spam/integrations
Custom tags/addons
Final CF7 addon project

2. What is Contact Form 7?

CF7 lets you design forms with form-tags and map submissions into mail templates. It is free, extensible, and widely used as a base for custom form workflows.

CF7 strengths

Free and open
Flexible HTML/form-tags
Mail templates with mail-tags
Rich action/filter hooks
Huge addon ecosystem

3. Installing and Activating Contact Form 7

Install like any plugin, activate, then open Contact in the admin menu to manage forms.

  1. Install Contact Form 7.
  2. Activate the plugin.
  3. Open Contact → Contact Forms.

Install path

Plugins → Add New → Contact Form 7 → Install → Activate

4. Contact Form 7 Dashboard

The Contact menu lists forms, lets you add new ones, and opens Integration for services like reCAPTCHA.

Main screens

Contact Forms list
Add New / Edit form
Integration (reCAPTCHA, etc.)

5. Creating Your First Contact Form

CF7 creates a default form on install. Duplicate or create new, then paste the shortcode into a page.

  1. Add or edit a form.
  2. Copy the shortcode.
  3. Paste into a page and publish.

Embed shortcode

[contact-form-7 id="123" title="Contact form"]

6. Contact Form 7 Form Editor

Each form has tabs for markup, outbound mail, user-facing messages, and advanced settings lines.

Editor tabs

Form → markup + form-tags
Mail → admin email
Mail (2) → auto-reply
Messages → success/errors
Additional Settings

7. Contact Form 7 Form Tags

Form-tags like `[text* your-name]` generate inputs. Options control IDs, classes, placeholders, and defaults.

Tag anatomy

[type* name id:foo class:bar placeholder "Hint"]
* = required
name = mail-tag key

8. Text Field in Contact Form 7

Use text fields for names and short answers. Prefer specialized tags (email, tel, url) when relevant.

Text tag

[text* your-name placeholder "Your name"]

9. Email Field in Contact Form 7

Email fields enforce format validation and pair well with mail headers.

Email tag

[email* your-email]
Reply-To: [your-email]

10. URL Field in Contact Form 7

Useful for portfolios, company sites, and lead qualification.

URL tag

[url your-website]

11. Telephone Field in Contact Form 7

Tel fields improve mobile keyboards and light format expectations.

Tel tag

[tel your-phone]

12. Number Field in Contact Form 7

Use for quantities, ages, or scores where numeric input is required.

Number tag

[number* qty min:1 max:99]

13. Date Field in Contact Form 7

Good for appointments and event inquiries; combine with clear labels for expected format.

Date tag

[date* preferred-date]

14. Textarea Field in Contact Form 7

Use for message bodies and descriptions. Set rows/cols or CSS for sizing.

Textarea tag

[textarea* your-message]

15. Dropdown Select Field in Contact Form 7

Dropdowns keep forms compact. Use `first_as_label` for a non-selectable placeholder option.

Select tag

[select* topic first_as_label "Choose topic" "Sales" "Support" "Other"]

16. Checkbox Field in Contact Form 7

Checkboxes suit multi-interest and consent-adjacent choices (use acceptance for legal consent when appropriate).

Checkbox tag

[checkbox interests "SEO" "Dev" "Design"]

17. Radio Button Field in Contact Form 7

Radios are ideal when exactly one option must be selected.

Radio tag

[radio budget default:1 "Under 1k" "1k-5k" "5k+"]

18. File Upload Field in Contact Form 7

Restrict filetypes and limit for security. Attach uploads in the Mail tab when needed.

File tag

[file* resume filetypes:pdf|doc|docx limit:2mb]

19. Acceptance Field in Contact Form 7

Use for privacy policy / terms acceptance. Pair with a link to your policy page.

Acceptance tag

[acceptance privacy] I agree to the privacy policy [/acceptance]

20. Quiz Field in Contact Form 7

Quiz fields ask a question with a known answer — lightweight spam friction.

Quiz tag

[quiz math "What is 2+3?|5"]

21. Hidden Fields in Contact Form 7

Hidden fields help tracking without cluttering the UI. Prefer server-side defaults when values must be trusted.

Hidden tag

[hidden source "homepage-hero"]

22. Submit Button in Contact Form 7

Change label text and add classes for styling.

Submit tag

[submit class:btn-primary "Send message"]

23. Required and Optional Fields in Contact Form 7

`text*` is required; `text` is optional. Only require fields you truly need.

Required vs optional

[text* your-name]  → required
[tel your-phone]   → optional

24. Custom Form HTML in Contact Form 7

CF7 Form tab accepts HTML around tags — use labels, wrappers, and grid classes freely.

Layout example

<label> Name
    [text* your-name] </label>

<label> Email
    [email* your-email] </label>

<label> Message
    [textarea* your-message] </label>

[submit "Send"]

25. Contact Form 7 Mail Settings

Mail settings define recipients, headers, subject, and body using mail-tags from your form.

Mail tabs

Mail → notify site owner
Mail (2) → optional auto-reply to sender

26. To, From and Reply-To in Contact Form 7

Use a site-owned From address when possible; put the visitor email in Reply-To.

Header pattern

To: you@example.com
From: Your Site <wordpress@example.com>
Reply-To: [your-name] <[your-email]>

27. Mail Subject and Headers in Contact Form 7

Subjects that include topic/name help inbox triage.

Subject example

Subject: [[topic]] inquiry from [your-name]

28. Mail Body and Form Tags in Contact Form 7

Each form-tag name becomes a mail-tag like `[your-message]`. Use `[_site_title]` and other special mail-tags too.

Body example

From: [your-name] <[your-email]>
Topic: [topic]

Message:
[your-message]

29. Additional Headers in Contact Form 7

Use Additional Headers for CC/BCC. Avoid spoofing From domains you do not control.

Additional headers

Cc: sales@example.com
Bcc: archive@example.com

30. File Attachments in Contact Form 7

Put the file field name in the Mail → File attachments box.

Attachments box

[resume]

31. Auto-Reply Emails in Contact Form 7

Enable Mail (2), set To to `[your-email]`, and write a clear thank-you body.

Mail 2 tip

To: [your-email]
Subject: We received your message
Body: thanks + next steps

32. Contact Form 7 Confirmation Messages

Clear messages improve trust when AJAX shows feedback without a page reload.

Message types

Mail sent successfully
Validation errors occurred
Acceptance missing
Upload failed
...

33. Success and Error Messages in Contact Form 7

Keep success actionable (expect reply time). Keep errors specific enough to fix inputs.

UX tip

Success → thank you + response time
Errors → tell which field failed

34. Contact Form 7 Validation

CF7 validates on submit (AJAX by default). Match field types to expected data.

Built-in validation

required (*)
email/url/tel/number formats
file type/size
acceptance checked

35. Custom Validation in Contact Form 7

Custom validation is ideal for phone formats, disposable email blocks, or cross-field rules.

Validation filter sketch

add_filter('wpcf7_validate_email*', function ($result, $tag) {
    // inspect posted value; $result->invalidate($tag, 'message');
    return $result;
}, 20, 2);

36. Form Submission Handling in Contact Form 7

Hooks let you abort mail, enrich data, or trigger side effects after a successful send.

Lifecycle

Submit (AJAX)
→ Validate
→ before_send_mail
→ Send mail
→ mail_sent / mail_failed
→ JSON response to browser

37. Contact Form 7 Actions and Filters

CF7 exposes many hooks for mail, validation, and AJAX responses. Prefix your callbacks.

Hook mindset

Actions → do something
Filters → change something
Never edit CF7 plugin files

38. wpcf7_before_send_mail Hook

`wpcf7_before_send_mail` is a key integration point for CRM sync and custom abort rules.

before_send_mail example

add_action('wpcf7_before_send_mail', function ($contact_form, &$abort, $submission) {
    // inspect $submission->get_posted_data();
    // set $abort = true to stop mail if needed
}, 10, 3);

39. wpcf7_mail_sent Hook

Use `wpcf7_mail_sent` for CRM pushes, Slack alerts, and analytics server events.

mail_sent example

add_action('wpcf7_mail_sent', function ($contact_form) {
    $submission = WPCF7_Submission::get_instance();
    if (! $submission) {
        return;
    }
    $data = $submission->get_posted_data();
    // sync $data
});

40. wpcf7_ajax_json_echo Hook

Useful for adding custom response data your front-end JS can consume.

ajax_json_echo sketch

add_filter('wpcf7_ajax_json_echo', function ($response, $result) {
    $response['acme_code'] = 'ok';
    return $response;
}, 10, 2);

41. Contact Form 7 AJAX

CF7 submits via AJAX and shows messages inline. Ensure your theme does not break CF7 scripts.

AJAX notes

Default: AJAX on
Depends on CF7 JS + jQuery events
Avoid dequeuing CF7 scripts globally

42. Custom JavaScript Events in Contact Form 7

Front-end events enable thank-you modals, GTM pushes, and pixel fires without editing CF7.

JS event example

document.addEventListener('wpcf7mailsent', function (event) {
  // event.detail.contactFormId
  // push to dataLayer / show modal
}, false);

43. Custom CSS Styling for Contact Form 7

Scope styles under `.wpcf7` so you do not break unrelated inputs.

Scoped CSS

.wpcf7 input[type="submit"] {
  border-radius: 8px;
  padding: 0.75rem 1.25rem;
}

44. Responsive Contact Forms with Contact Form 7

Test labels, errors, file inputs, and submit on small screens.

Mobile QA

Readable labels
Full-width inputs
No overflow
Tap-friendly submit

45. Multi-Step Contact Forms with Contact Form 7

CF7 is single-form by default — multi-step usually needs custom JS or an extension.

Approach options

Fieldset steps + JS show/hide
Helper plugin for multi-step
Separate forms per step (advanced)

46. Conditional Fields in Contact Form 7

Conditional logic keeps forms short. Validate only visible required fields carefully.

Conditional tip

If topic=Support → show ticket fields
Test required fields when hidden

47. Dynamic Form Fields in Contact Form 7

Use hooks/shortcodes or custom form-tags to inject user, post, or query data.

Dynamic idea

// Prefill logged-in user email via filter/custom tag
// Or set hidden post ID from queried object

48. Dependent Dropdowns in Contact Form 7

Keep option lists maintainable in JS/JSON and sync posted values with server validation.

Cascade pattern

Parent select change
→ rebuild child options
→ clear invalid child value

49. Custom Form Tag Development in Contact Form 7

Custom tags need generator UI (optional), rendering callback, and validation support.

Register tag sketch

add_action('wpcf7_init', function () {
    wpcf7_add_form_tag('acme_rating', 'acme_rating_handler', ['name-attr' => true]);
});

50. Contact Form 7 REST API

CF7 exposes REST routes for contact forms feedback — authenticate and validate carefully on custom clients.

REST tip

Prefer official feedback endpoints
Send required unit-tag/nonce style params
Handle validation JSON errors

51. Contact Form 7 Database Integration

CF7 does not store entries by default — add Flamingo/custom storage when you need history.

Storage options

Flamingo (by CF7 author)
Third-party entry plugins
Custom table via hooks

52. Saving Form Entries from Contact Form 7

Decide retention and privacy before storing personal data.

Save on mail_sent

add_action('wpcf7_mail_sent', function ($form) {
    $submission = WPCF7_Submission::get_instance();
    $data = $submission ? $submission->get_posted_data() : [];
    // insert into custom table / CRM
});

53. Custom Database Tables for Contact Form 7

Use `$wpdb`, prepare statements, and store form ID + timestamps.

Insert sketch

global $wpdb;
$wpdb->insert($wpdb->prefix . 'acme_cf7_leads', [
    'form_id' => $form->id(),
    'email'   => sanitize_email($data['your-email'] ?? ''),
    'created' => current_time('mysql'),
]);

54. Contact Form 7 + Google reCAPTCHA

Add site/secret keys, then reCAPTCHA protects CF7 forms automatically when configured.

Setup

Contact → Integration → reCAPTCHA
Add keys → Save
Test submit + spam attempt

55. Contact Form 7 + Akismet

Akismet can evaluate message content when configured correctly with CF7.

Spam tip

Activate Akismet
Ensure CF7 fields map usefully
Review false positives

56. Spam Protection for Contact Form 7

No single defense is perfect — combine friction with server-side checks.

Spam layers

reCAPTCHA / Turnstile-style
Akismet
Quiz / honeypot
Custom reject filters

57. Honeypot Integration with Contact Form 7

Implement via addon or custom tag + validation reject when filled.

Honeypot idea

Hidden CSS field
If filled → invalidate submission
Keep accessible to real users

58. Contact Form 7 + Google Sheets

Useful for lightweight reporting; protect sheet access and PII.

Sheets options

Dedicated CF7 Sheets addon
Zapier → Google Sheets
Webhook → Apps Script

59. Contact Form 7 + Mailchimp

Map email/name fields and respect consent/opt-in rules.

Mailchimp checklist

API key / OAuth
List/audience map
Consent field if required
Test subscribe

60. Contact Form 7 + CRM Integration

Use native connectors, Zapier, or `wpcf7_mail_sent` API calls.

CRM tip

Dedupe on email
Set lead source
Notify owner

61. Contact Form 7 + Zapier

Trigger zaps from new submissions via webhook/email parser/helper plugins.

Zap idea

Trigger: new CF7 submit
Action: Slack + Sheet + CRM contact

62. Contact Form 7 + Webhooks

Webhooks enable custom backends with retries and signature verification.

Webhook sketch

add_action('wpcf7_mail_sent', function ($form) {
    $submission = WPCF7_Submission::get_instance();
    $payload = $submission ? $submission->get_posted_data() : [];
    wp_remote_post('https://example.com/hook', [
        'timeout' => 8,
        'headers' => ['Content-Type' => 'application/json'],
        'body' => wp_json_encode($payload),
    ]);
});

63. Contact Form 7 + WhatsApp

Use compliant providers and obtain consent where required.

WhatsApp tip

Staff alert on new lead
User confirmation carefully
Respect opt-in rules

64. Contact Form 7 + SMS Notifications

Keep messages short; do not SMS secrets; rate-limit abuse.

SMS flow

mail_sent → format message → provider API → log result

65. Contact Form 7 + SMTP

Use an SMTP plugin (or custom `phpmailer_init`) with SPF/DKIM-aligned From domains.

SMTP checklist

SMTP plugin configured
From domain authenticated
Test to multiple inboxes
Check spam folder

66. Contact Form 7 + Google Analytics

Track form_id and conversion events in dataLayer/gtag.

GA4 event sketch

document.addEventListener('wpcf7mailsent', function (event) {
  gtag('event', 'generate_lead', {
    form_id: event.detail.contactFormId
  });
});

67. Contact Form 7 + Facebook Pixel

Fire `fbq('track', 'Lead')` inside `wpcf7mailsent` and match Pixel ID setup.

Pixel sketch

document.addEventListener('wpcf7mailsent', function () {
  if (typeof fbq === 'function') {
    fbq('track', 'Lead');
  }
});

68. Contact Form 7 + Payment Integration

CF7 is not a full checkout — payment addons/custom code add charge steps.

Payment approaches

CF7 payment addon
Redirect to hosted checkout
Custom gateway addon

69. Stripe Payment Integration with Contact Form 7

Prefer official/well-maintained addons or Payment Intents with server confirmation.

Stripe checklist

Test mode keys
Amount + currency
Success/fail UX
Store payment intent id

70. PayPal Payment Integration with Contact Form 7

Test sandbox first; confirm paid status before fulfilling.

PayPal tip

Sandbox → live
Match currency
Verify completed payments

71. Authorize.Net Payment Integration with Contact Form 7

Protect API credentials and validate AVS/CVV settings with your account.

Auth.Net tip

API Login + Transaction Key
Test mode
Decline handling

72. Recurring Payment Forms with Contact Form 7

Disclose intervals clearly and provide cancellation instructions.

Recurring UX

Show plan interval
Terms disclosure
Receipt email
Cancel path

73. Donation Forms with Contact Form 7

Offer suggested amounts plus custom amount; send receipts immediately.

Donation fields

Amount select + custom
Donor details
Payment method
Receipt confirmation

74. Order Forms with Contact Form 7

For complex carts/shipping, consider WooCommerce instead.

Order form pieces

Product/options
Qty
Total display
Payment + fulfillment email

75. PDF Generation from Contact Form 7

Use PDF addons or libraries (TCPDF/Dompdf) triggered on `wpcf7_mail_sent`.

PDF flow

Collect posted data → render template → save PDF → attach/email/link

76. Custom PDF Templates for Contact Form 7

Keep templates simple; escape values before inserting into HTML-to-PDF.

Template tip

Logo + title
Field table
Footer date/ref id

77. Form Submission PDF Attachments in Contact Form 7

Generate before send (carefully) or email a secure download link after save.

Attachment options

Attach to Mail
Store in uploads (protected)
Link in auto-reply

78. Email OTP Authentication with Contact Form 7

OTP flows need rate limits, expiry, and careful UX — often as a custom addon.

OTP steps

User enters email → send code
User submits code → verify
Allow form completion / mark verified

79. Custom OTP Verification for Contact Form 7

Never store OTPs in plaintext; throttle attempts; invalidate after success.

OTP security

Hash codes
Short TTL
Attempt limits
Single use

80. User Registration with Contact Form 7

Map fields carefully, set safe default roles, and never allow arbitrary role selection from public forms.

Registration sketch

add_action('wpcf7_mail_sent', function () {
    // wp_insert_user with sanitized email/login/password
    // assign safe default role
});

81. Login Forms with Contact Form 7

If using CF7-like UI, still authenticate with WordPress APIs and secure redirects.

Login caution

Use WP auth APIs
Protect against enumeration
Redirect after login
Prefer purpose-built login UX for complex membership

82. Contact Form 7 Custom Addon Development

Check for CF7 on `plugins_loaded`, then register tags, hooks, and settings.

Addon bootstrap

add_action('plugins_loaded', function () {
    if (! defined('WPCF7_VERSION')) {
        return;
    }
    // boot addon
});

83. Contact Form 7 Plugin Architecture

Knowing `WPCF7_ContactForm` and `WPCF7_Submission` helps you write safer addons.

Key concepts

Contact form post type/object
Form-tags / mail-tags
WPCF7_Submission
Mail templates
REST/AJAX feedback

84. Creating Custom Addons for Contact Form 7

Include readme, versioning, and graceful admin notices when CF7 is missing.

Plugin header

<?php
/**
 * Plugin Name: Acme CF7 Extension
 * Description: Custom Contact Form 7 addon.
 * Version: 1.0.0
 * Text Domain: acme-cf7
 */

85. Custom Admin Settings for CF7 Addons

Sanitize options on save; never expose secrets to the front end.

Settings tip

register_setting('acme_cf7', 'acme_cf7_settings', [
    'type' => 'array',
    'sanitize_callback' => 'acme_cf7_sanitize_settings',
]);

86. Custom Form Tags in Contact Form 7 Addons

Document tag syntax for users and support validation + mail-tag output.

Custom tag checklist

Register on wpcf7_init
Render HTML
Validate
Mail-tag value
Docs/examples

87. Custom Form Validation in CF7 Addons

Invalidate with clear messages; don’t rely only on client-side checks.

Validation tip

Use wpcf7_validate_{type} filters
Return $result unchanged when OK
Invalidate with user-safe messages

88. Custom Payment Gateway Addon for Contact Form 7

Implement credentials, amount mapping, payment processing, and failure messages.

Gateway scope

Settings credentials
Amount source field
Process on submit
Store transaction id
Handle webhooks

89. Custom API Integration with Contact Form 7

Prefer `wpcf7_mail_sent` for success-only sync; use before_send_mail when abort matters.

API sync tip

timeout + error log
idempotency key
don’t block UX on slow APIs without care

90. Contact Form 7 Security

Keep CF7 updated; restrict filetypes; protect stored entries; secure custom endpoints.

Security basics

Update CF7 + addons
Limit uploads
Spam protection
Secure custom AJAX/REST

91. Nonces and CSRF Protection in CF7 Addons

CF7 forms include their own protections; your addon endpoints still need WordPress nonces.

Nonce check

check_ajax_referer('acme_cf7', 'nonce');
if (! current_user_can('manage_options')) {
    wp_send_json_error(null, 403);
}

92. Data Sanitization and Escaping for CF7

Treat posted values as untrusted even after CF7 validation.

Examples

$email = sanitize_email($data['your-email'] ?? '');
echo esc_html($name);

93. SQL Injection Prevention with Contact Form 7 Data

Never concatenate raw posted strings into SQL.

Safe query

$wpdb->get_results($wpdb->prepare(
    "SELECT * FROM {$wpdb->prefix}acme_cf7_leads WHERE email = %s",
    $email
));

94. XSS Protection for Contact Form 7

Be careful with HTML emails and PDF HTML templates — escape field values.

XSS tip

esc_html / esc_attr on output
wp_kses for limited HTML
Don’t trust mail body placeholders unescaped in custom UIs

95. Contact Form 7 Debugging

Check Messages tab, browser console, SMTP, and plugin conflicts systematically.

Debug checklist

Does AJAX response return?
Mail vs Mail(2)?
SMTP working?
Console JS errors?
Conflict test (default theme)

96. Performance Optimization for Contact Form 7

Avoid heavy global scripts from addons; optimize host SMTP latency.

Perf tips

Conditional asset loading
Lean addons
Fast SMTP
Don’t over-validate remotely without timeouts

97. WordPress Coding Standards for CF7 Addons

Prefix everything, internationalize strings, escape/sanitize consistently.

Standards focus

Prefixing
i18n
Escaping/sanitizing
Capability checks

98. WordPress.org Plugin Guidelines for CF7 Addons

No phone-home abuse, proper licensing, no obfuscation, and clear readme data.

Guidelines themes

GPL-compatible
No tracking without disclosure
Human-readable code
Honest readme

99. Contact Form 7 Addon Testing

Always run a real form submit on staging across caching and common themes.

Test checklist

Form renders
Required validation
Mail delivered
Hooks fired
No PHP notices
JS events fire

100. Final Project – Complete Contact Form 7 Addon Development

Create a professional addon that requires CF7, stores API settings, selects forms to sync, posts submission JSON to an endpoint on `wpcf7_mail_sent`, logs failures, and ships with readme + test checklist.

  1. Define API destination and payload shape.
  2. Implement settings + mail_sent sync.
  3. Add logging and failure handling.
  4. Document and test on staging.

Final project scope

1. Plugin bootstrap + WPCF7_VERSION check
2. Settings page (API URL, key, form IDs)
3. wpcf7_mail_sent handler
4. wp_remote_post with timeout + logging
5. Admin notice if CF7 missing
6. readme.txt + changelog
7. Staging test checklist

Starter bootstrap

<?php
/**
 * Plugin Name: Acme CF7 Sync
 * Description: Final project — sync CF7 submissions to an API.
 * Version: 1.0.0
 * Text Domain: acme-cf7-sync
 */

if (! defined('ABSPATH')) {
    exit;
}

add_action('plugins_loaded', function () {
    if (! defined('WPCF7_VERSION')) {
        add_action('admin_notices', function () {
            echo '<div class="notice notice-error"><p>Acme CF7 Sync requires Contact Form 7.</p></div>';
        });
        return;
    }
    require_once __DIR__ . '/includes/class-acme-cf7-sync.php';
    AcmeCF7SyncPlugin::instance(__FILE__)->boot();
});

Conclusion

You now have a full Contact Form 7 path: form-tags, mail, validation, spam and integrations, plus hooks for custom addons. Finish the final addon project to turn the lessons into a shippable extension.

Leave a reply

Your email address will not be published. Required fields are marked *