The code below demonstrates how to insert data from a Contact Form 7 submission into a custom table in WordPress. This code should be placed in your theme’s functions.php
file.
First, ensure you have created a custom table in your WordPress database.
add_action('wpcf7_before_send_mail','save_form');
function save_form( $wpcf7 ){
global $wpdb;
$submission = WPCF7_Submission::get_instance();//get form data
if ($submission){
$submited = array();
$submited['title'] = $wpcf7->title();
$submited['posted_data'] = $submission->get_posted_data(); //get submitted data
}
if(!empty($submited)){
$current_uid = get_current_user_id();
$wpdb->insert( $wpdb->prefix.'events',//table name events
array(
'name' =>$submited['posted_data']['your-name'], //identifier for name provided in wpcf7
'email' =>$submited['posted_data']['your-email'], //identifier for email provided in wpcf7
'invoice' =>$submited['posted_data']['invoice'], //identifier for invoice provided in wpcf7
'uid' =>$current_uid, 'timestamp' =>time(),
)
);
}
}
Explanation of the Code:
- Hook into the Form Submission:
- The
add_action('wpcf7_before_send_mail','save_form');
line hooks into the form submission process of Contact Form 7, triggering thesave_form
function before the email is sent.
- The
- Retrieve the Submitted Data:
- The
WPCF7_Submission::get_instance();
method gets the instance of the form submission. $submited['posted_data'] = $submission->get_posted_data();
retrieves the data that was submitted through the form.
- The
- Prepare the Data for Insertion:
- The code checks if there is any submitted data and then collects the current user ID with
get_current_user_id();
.
- The code checks if there is any submitted data and then collects the current user ID with
- Insert Data into the Custom Table:
- The
$wpdb->insert
function inserts the form data into the custom tablewp_events
. - It includes fields such as
name
,email
,invoice
,uid
, andtimestamp
.
- The
Additional Notes:
- Custom Table Creation: Ensure that the custom table (
wp_events
in this case) is created in your WordPress database before using this code. You can adjust the table name and fields according to your needs. - Security Considerations: The data sanitization functions such as
sanitize_text_field
andsanitize_email
are used to ensure that the input data is clean and safe before being inserted into the database. Add similar sanitization functions for all data fields. - Debugging and Logging: It might be helpful to add some error handling or logging to capture any issues during the data insertion process. This can be done using
error_log
or by adding custom logging functionality.
This setup allows you to efficiently capture and store data from Contact Form 7 submissions into a custom database table, facilitating further processing or analysis as required by your application.
4o