How to Save Contact Form Data in the WordPress Database

Introduction: Why Store Contact Form Data in the WordPress Database?
Storing contact form data directly within the WordPress database offers numerous advantages over relying solely on email notifications. While email is convenient, it’s prone to delivery issues, spam filters, and accidental deletion. Database storage provides a reliable, searchable, and manageable archive of all submissions. This data can be invaluable for:
- Lead generation and tracking
- Customer relationship management (CRM)
- Analyzing user feedback and improving your website
- Compliance with data privacy regulations (GDPR, CCPA)
- Creating reports and dashboards
- Preventing data loss due to email problems
Several methods exist for achieving this, ranging from using specialized plugins to writing custom code. The best approach depends on your technical skill level and specific requirements.
Method 1: Utilizing Contact Form Plugins with Database Storage Features
Many popular contact form plugins natively offer database storage functionality. This is often the easiest and most user-friendly approach, especially for those without coding experience. Some prominent plugins with this feature include:
- Contact Form 7: With the “Flamingo” plugin (developed by the same author), Contact Form 7 can store submissions in the WordPress database.
- WPForms: WPForms offers a built-in “Entries” section where you can view, search, and export form submissions.
- Gravity Forms: Gravity Forms is a premium plugin with robust features, including advanced database storage and integration capabilities.
- Formidable Forms: Formidable Forms provides a comprehensive solution for creating and managing forms, with built-in database storage and reporting features.
Let’s examine the steps for storing data using Contact Form 7 with Flamingo:
- Install and activate the Contact Form 7 plugin.
- Install and activate the Flamingo plugin (by Takayuki Miyoshi).
- Create or edit your contact form using the Contact Form 7 interface.
- Flamingo automatically captures and stores all submissions from your Contact Form 7 forms in the “Inbound Messages” section of the WordPress admin dashboard. No further configuration is usually needed.
- You can then view, search, and export the submissions from within Flamingo.
WPForms provides an even simpler experience:
- Install and activate the WPForms plugin.
- Create your contact form using the WPForms drag-and-drop builder.
- By default, WPForms stores all form submissions in the WordPress database.
- Navigate to “WPForms” -> “Entries” in the WordPress admin dashboard to view, search, and manage your form submissions. You can also export the data to CSV format.
Gravity Forms and Formidable Forms offer similar functionalities, often with more advanced features like conditional logic, user registration, and integration with other services. These plugins typically handle database storage automatically, requiring minimal configuration.
Method 2: Creating a Custom Contact Form and Database Storage using PHP
For those comfortable with PHP and WordPress development, creating a custom contact form and implementing database storage provides greater flexibility and control. This method involves creating a form, handling form submission, validating data, and inserting the data into a custom database table.
**Step 1: Create the Contact Form HTML**
First, create the HTML markup for your contact form within a WordPress page or template. Here’s a basic example:
“`html
“`
**Step 2: Create a Custom Database Table**
Create a custom database table to store the contact form data. You can use a plugin like “Custom Database Tables” or manually execute SQL queries using phpMyAdmin or a similar tool. Here’s an example SQL query to create a table named `wp_contact_form_submissions`:
“`sql
CREATE TABLE wp_contact_form_submissions (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
message TEXT NOT NULL,
submission_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
“`
Remember to use the correct WordPress table prefix (usually `wp_`) to avoid conflicts with other plugins.
**Step 3: Handle Form Submission and Database Insertion**
Add the following PHP code to your theme’s `functions.php` file (or a custom plugin) to handle the form submission, validate the data, and insert it into the database:
“`php
Invalid email address.
‘;
return;
}
// Access the WordPress database object
global $wpdb;
$table_name = $wpdb->prefix . ‘contact_form_submissions’;
// Insert data into the database
$result = $wpdb->insert(
$table_name,
array(
‘name’ => $name,
’email’ => $email,
‘message’ => $message,
),
array(‘%s’, ‘%s’, ‘%s’) // Data types for each field
);
if ($result) {
echo ‘
Thank you for your submission!
‘;
} else {
echo ‘
An error occurred while submitting the form. Please try again.
‘;
error_log(“Error inserting data into the database: ” . $wpdb->last_error); // Log the error
}
}
}
// Enqueue JavaScript for AJAX handling (optional)
function enqueue_custom_contact_form_script() {
wp_enqueue_script(‘custom-contact-form’, get_stylesheet_directory_uri() . ‘/js/custom-contact-form.js’, array(‘jquery’), ‘1.0’, true);
wp_localize_script(‘custom-contact-form’, ‘ajax_object’, array(‘ajax_url’ => admin_url(‘admin-ajax.php’)));
}
add_action(‘wp_enqueue_scripts’, ‘enqueue_custom_contact_form_script’);
// AJAX handler function (if using AJAX)
add_action(‘wp_ajax_handle_custom_contact_form’, ‘handle_custom_contact_form’);
add_action(‘wp_ajax_nopriv_handle_custom_contact_form’, ‘handle_custom_contact_form’);
// Shortcode to display the form (optional)
function custom_contact_form_shortcode() {
ob_start();
handle_custom_contact_form(); // Execute the form handling function
?>
“`
This code performs the following actions:
- Defines a function `handle_custom_contact_form()` to process the form submission.
- Sanitizes and validates the input data using `sanitize_text_field()`, `sanitize_email()`, and `sanitize_textarea_field()`.
- Checks if the email address is valid using `is_email()`.
- Accesses the WordPress database object using `$wpdb`.
- Constructs the table name using `$wpdb->prefix` to ensure compatibility with different WordPress installations.
- Inserts the data into the database using `$wpdb->insert()`.
- Displays a success or error message based on the result of the database insertion.
- Includes enqueue functions for front end scripts and styles.
- Creates a shortcode `[custom_contact_form]` to easily embed the form on any page or post.
**Step 4: Display the Form and Handle the Submission**
You can now display the contact form on a page or post by using the shortcode `[custom_contact_form]`. When the form is submitted, the `handle_custom_contact_form()` function will be executed, and the data will be stored in the `wp_contact_form_submissions` table.
**Step 5: (Optional) Implement AJAX Submission**
To improve the user experience, you can implement AJAX submission to prevent the page from reloading after the form is submitted. This requires writing some JavaScript code.
Create a file named `custom-contact-form.js` in your theme’s directory (or a subdirectory like `js`) and add the following code:
“`javascript
jQuery(document).ready(function($) {
$(‘#custom-contact-form’).submit(function(e) {
e.preventDefault();
var formData = $(this).serialize();
$.ajax({
url: ajax_object.ajax_url,
type: ‘POST’,
data: formData + ‘&action=handle_custom_contact_form’,
dataType: ‘html’,
success: function(response) {
$(‘#form-response’).html(response);
// Clear the form fields on success (optional)
$(‘#custom-contact-form’)[0].reset();
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(‘AJAX error: ‘ + textStatus + ‘ – ‘ + errorThrown);
$(‘#form-response’).html(‘
An error occurred. Please try again later.
‘);
}
});
});
});
“`
This JavaScript code performs the following actions:
- Prevents the default form submission behavior.
- Serializes the form data into a string.
- Sends an AJAX request to the `admin-ajax.php` file, specifying the `action` parameter as `handle_custom_contact_form`.
- Displays the response from the server in the `#form-response` div.
- Clears the form fields on successful submission (optional).
- Handles potential errors during the AJAX request.
Make sure that the JavaScript file is properly enqueued using the `wp_enqueue_scripts` action, as shown in the PHP code above. The `wp_localize_script` function is used to pass the `ajax_url` variable to the JavaScript file.
Method 3: Using WordPress Hooks and the `wp_mail` Function
This approach combines the built-in `wp_mail` function for sending email notifications with custom code to store the data in the database. It involves hooking into the `wp_mail` action to intercept the email content before it is sent and then inserting the data into the database.
This method is useful when you want to maintain the email notification functionality while also storing the data in the database. It’s particularly relevant if you’re using a simple form that relies on `wp_mail` for sending submissions.
Here’s how you can implement this method:
**Step 1: Ensure Your Form Uses `wp_mail`**
This method assumes your form (either custom-built or created with a simple plugin) uses the `wp_mail` function to send submissions. This function is a core WordPress function for sending emails. If your form uses a different method, you’ll need to adjust the approach accordingly.
**Step 2: Hook into the `wp_mail` Action**
Add the following code to your theme’s `functions.php` file (or a custom plugin):
“`php
prefix . ‘contact_form_submissions’;
// Insert data into the database
$result = $wpdb->insert(
$table_name,
array(
‘name’ => $name,
’email’ => $email,
‘message’ => $message_content,
),
array(‘%s’, ‘%s’, ‘%s’) // Data types for each field
);
if (!$result) {
error_log(“Error inserting data into the database: ” . $wpdb->last_error);
}
}
return $args; // Return the original arguments to ensure the email is still sent
}
?>
“`
This code performs the following actions:
- Hooks into the `wp_mail` filter using `add_filter()`.
- Defines a function `store_contact_form_data()` that will be executed whenever `wp_mail` is called.
- Checks if the email is a contact form submission by examining the subject line (you might need to adjust this logic based on your specific form).
- Extracts the name, email, and message from the email content using regular expressions (this part is crucial and will depend on the exact format of your email messages).
- Sanitizes the extracted data using `sanitize_text_field()`, `sanitize_email()`, and `sanitize_textarea_field()`.
- Accesses the WordPress database object using `$wpdb`.
- Inserts the data into the `wp_contact_form_submissions` table.
- Returns the original `$args` array to ensure that the email is still sent.
**Important Considerations for Method 3:**
- **Email Format:** This method heavily relies on the consistent format of your email messages. If the format changes, the regular expressions will need to be updated.
- **Error Handling:** The code includes basic error logging, but you should implement more robust error handling to catch potential issues.
- **Security:** Ensure that you properly sanitize and validate the extracted data to prevent security vulnerabilities.
- **Performance:** Hooking into `wp_mail` can potentially impact performance if the function is called frequently. Consider the performance implications, especially on high-traffic sites.
- **Specificity:** The subject line check (`strpos($args[‘subject’], ‘Contact Form Submission’) !== false`) is a simple way to identify contact form emails. For more reliable identification, consider adding a unique identifier or custom header to your contact form emails.
Conclusion: Choosing the Right Method
The best method for saving contact form data in the WordPress database depends on your technical expertise and the complexity of your requirements.
- **For beginners and those seeking simplicity:** Using a contact form plugin with built-in database storage is the recommended approach. Plugins like Contact Form 7 (with Flamingo), WPForms, Gravity Forms, and Formidable Forms provide user-friendly interfaces and automatic data storage.
- **For developers who need greater control:** Creating a custom contact form and implementing database storage using PHP offers the most flexibility. This method requires coding knowledge but allows you to tailor the form and data storage to your exact needs.
- **For maintaining existing email workflows while adding database storage:** Hooking into the `wp_mail` function can be a viable option, but it requires careful attention to email formatting and error handling.
Regardless of the method you choose, always prioritize data sanitization and validation to protect your website from security vulnerabilities. Properly storing contact form data in the WordPress database can significantly improve your lead generation, customer relationship management, and website analysis capabilities.
- How to Completely Customize Your WordPress RSS Feeds
- WordPress Playground – How to Use WordPress in Your Browser
- How to Show a Floating Contact Form in WordPress (3 Methods)
- How to Set, Get, and Delete WordPress Cookies (Like a Pro)
- How to Create a Custom Calculator in WordPress (Step by Step)
- How to Add Slide Out Contact Form in WordPress (Easy Tutorial)
- How to Easily Create a Staging Site for WordPress (Step by Step)