One Contact Form 7 Submission per Logged-In User
Lets each logged-in member send the Contact Form 7 forms you choose only once, for surveys, applications or votes, and shows a message instead of the form afterwards.
Opens WPIDE on
Code
$wpide_cf7_once_forms = array(); // Form IDs, e.g. array( 123 ).
$wpide_cf7_once_message = 'You have already submitted this form. Thank you!';
add_action( 'wpcf7_mail_sent', function ( $contact_form ) use ( $wpide_cf7_once_forms ) {
if ( is_user_logged_in() && in_array( (int) $contact_form->id(), array_map( 'intval', $wpide_cf7_once_forms ), true ) ) {
update_user_meta( get_current_user_id(), '_wpide_cf7_done_' . (int) $contact_form->id(), time() );
}
} );
add_filter( 'wpcf7_spam', function ( $spam ) use ( $wpide_cf7_once_forms ) {
$form = function_exists( 'wpcf7_get_current_contact_form' ) ? wpcf7_get_current_contact_form() : null;
if ( $form && is_user_logged_in() && in_array( (int) $form->id(), array_map( 'intval', $wpide_cf7_once_forms ), true ) && get_user_meta( get_current_user_id(), '_wpide_cf7_done_' . (int) $form->id(), true ) ) {
return true;
}
return $spam;
}, 40 );
add_filter( 'do_shortcode_tag', function ( $output, $tag, $attr ) use ( $wpide_cf7_once_forms, $wpide_cf7_once_message ) {
if ( 'contact-form-7' !== $tag || empty( $attr['id'] ) || ! is_user_logged_in() || ! function_exists( 'wpcf7_contact_form' ) ) {
return $output;
}
$form = wpcf7_contact_form( $attr['id'] );
$id = $form ? (int) $form->id() : 0;
if ( in_array( $id, array_map( 'intval', $wpide_cf7_once_forms ), true ) && get_user_meta( get_current_user_id(), '_wpide_cf7_done_' . $id, true ) ) {
return '<p class="wpide-form-closed" role="status">' . esc_html( $wpide_cf7_once_message ) . '</p>';
}
return $output;
}, 10, 3 );
Notes
List the form IDs at the top and combine with CF7's "subscribers_only: true" additional setting so only logged-in users can use the form.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.