I am trying to save to my database, the submissions from my contact form 7 form. I found some functions (don't know the author) to do so. It works, but it won't save the option selected from the drop-down menus to the database. I don't know what I am missing. I tried this:
add_action("wpcf7_submit", "SE_379325_forward_cf7", 10, 2);
function SE_379325_forward_cf7($form, $result) {
if( !class_exists('WPCF7_Submission') )
return;
$submission = WPCF7_Submission::get_instance();
if ($result["status"] == "mail_sent") { // proceed only if email has been sent
$posted_data = $submission->get_posted_data();
save_posted_data($posted_data);
}
};
// your insert function:
function save_posted_data($posted_data){
$form_id = $posted_data["_wpcf7"]; // this is the post->ID of the submitted form so if you have more than one you can decide whether or not to save this form fields
if($form_id == 403)
return;
global $wpdb;
$wpdb->insert(
$wpdb->prefix.'tabletest',
array(
'lastname'=>$posted_data['lastName'],
'name'=>$posted_data['firstName'],
'email'=>$posted_data['email'],
'phone'=>$posted_data['tel-3'],
'subject'=>$posted_data['menu-338'],
'role'=>$posted_data['menu-761'],
'message'=>$posted_data['your-message'],
'thedate'=>$posted_data['date-288']
),
array('%s')
);
}
The fields I cannot save are 'subject' and 'role'. They are just empty on my table columns.
This is my form from Contact Form 7
I would appreciate any help.
Two potential problems.
$contact_form->id
in the first submit
function.I've added sanitization as well, you can alter as needed. CF7 Doesn't by default sanitize data since it's just input in/input out, and not stored anywhere.
add_action( 'wpcf7_submit', 'SE_379325_forward_cf7', 10, 2 );
function SE_379325_forward_cf7( $form, $result ) {
if ( ! class_exists( 'WPCF7_Submission' ) ) {
return;
}
$submission = WPCF7_Submission::get_instance();
if ( 'mail_sent' === $result['status'] ) { // proceed only if email has been sent.
$posted_data = $submission->get_posted_data();
save_posted_data( $posted_data, $form->id );
}
}
// your insert function.
function save_posted_data( $posted_data, $form_id ) {
if ( 403 !== $form_id ) {
global $wpdb;
$wpdb->insert(
$wpdb->prefix . 'tabletest',
array(
'lastname' => sanitize_text_field( wp_unslash( $posted_data['lastName'] ) ),
'name' => sanitize_text_field( wp_unslash( $posted_data['firstName'] ) ),
'email' => sanitize_text_field( wp_unslash( $posted_data['email'] ) ),
'phone' => sanitize_email( wp_unslash( $posted_data['tel-3'] ) ),
'subject' => sanitize_text_field( wp_unslash( $posted_data['menu-338'][0] ) ),
'role' => sanitize_text_field( wp_unslash( $posted_data['menu-761'][0] ) ),
'message' => sanitize_textarea_field( wp_unslash( $posted_data['your-message'] ) ),
'thedate' => sanitize_text_field( wp_unslash( $posted_data['date-288'] ) ),
),
array( '%s' )
);
}
}