Introduction:
I’m developing a WordPress plugin that manages submissions from Contact Form 7. I need to prevent the form from sending emails if a duplicate submission is detected based on the form’s date field (date-123) for the same user.
Context:
I’ve implemented a custom validation filter to detect duplicates and it seems to be working, but the emails are still being sent even when duplicates are found. I want to ensure that no email is sent if a duplicate submission is detected. I’ve tried using the skip_mail: on setting in the Additional Settings field, which successfully stops the emails, but the correct pop-up message for validation failure is not triggered.
What I Have Tried:
I’ve added a custom validation filter to Contact Form 7 to check for duplicates:
function cf7_manager_custom_validation_filter($result, $tag) {
global $wpdb, $cf7_manager_user_id;
if ('date-123' === $tag->name) {
$submission = WPCF7_Submission::get_instance();
if ($submission) {
$data = $submission->get_posted_data();
$user_id = $cf7_manager_user_id;
$form_post_id = $submission->get_contact_form()->id();
$date = $data['date-123'];
if (cf7_manager_check_duplicate_submission($form_post_id, $user_id, $date)) {
$result->invalidate($tag, 'You have already made a submission for this date.');
}
}
}
return $result;
}
add_filter('wpcf7_validate_text', 'cf7_manager_custom_validation_filter', 20, 2);
add_filter('wpcf7_validate_text*', 'cf7_manager_custom_validation_filter', 20, 2);
function cf7_manager_check_duplicate_submission($form_post_id, $user_id, $date) {
global $wpdb;
$cfdb = apply_filters('cf7_manager_database', $wpdb);
$table_name = $cfdb->prefix . 'cf7_manager_forms';
$query = $cfdb->prepare(
"SELECT COUNT(*) FROM $table_name WHERE form_post_id = %d AND user_id = %d AND form_value LIKE %s",
$form_post_id,
$user_id,
'%' . $cfdb->esc_like('"date-123";s:' . strlen($date) . ':"' . $date . '"') . '%'
);
$count = $cfdb->get_var($query);
return $count > 0;
}
function cf7_manager_check_duplicate_submission($form_post_id, $user_id, $date) {
global $wpdb;
$cfdb = apply_filters('cf7_manager_database', $wpdb);
$table_name = $cfdb->prefix . 'cf7_manager_forms';
$query = $cfdb->prepare(
"SELECT COUNT(*) FROM $table_name WHERE form_post_id = %d AND user_id = %d AND form_value LIKE %s",
$form_post_id,
$user_id,
'%' . $cfdb->esc_like('"date-123";s:' . strlen($date) . ':"' . $date . '"') . '%'
);
$count = $cfdb->get_var($query);
return $count > 0;
}