Close a Contact Form 7 Form After a Number of Entries
Accepts only a set number of successful submissions for a Contact Form 7 form, such as event places or giveaway entries, then shows a "closed" message instead of the form.
Opens WPIDE on
Code
// Form ID => maximum successful submissions.
$wpide_cf7_limits = array(); // e.g. array( 123 => 50 ).
$wpide_cf7_closed_message = 'Sorry, this form is closed because all places have been taken.';
add_action( 'wpcf7_mail_sent', function ( $contact_form ) use ( $wpide_cf7_limits ) {
$id = (int) $contact_form->id();
if ( isset( $wpide_cf7_limits[ $id ] ) ) {
update_option( 'wpide_cf7_count_' . $id, (int) get_option( 'wpide_cf7_count_' . $id, 0 ) + 1, false );
}
} );
add_filter( 'wpcf7_validate', function ( $result ) use ( $wpide_cf7_limits, $wpide_cf7_closed_message ) {
$form = function_exists( 'wpcf7_get_current_contact_form' ) ? wpcf7_get_current_contact_form() : null;
$id = $form ? (int) $form->id() : 0;
if ( isset( $wpide_cf7_limits[ $id ] ) && (int) get_option( 'wpide_cf7_count_' . $id, 0 ) >= $wpide_cf7_limits[ $id ] ) {
$tags = $form->scan_form_tags();
if ( $tags ) {
$result->invalidate( $tags[0], $wpide_cf7_closed_message );
}
}
return $result;
} );
add_filter( 'do_shortcode_tag', function ( $output, $tag, $attr ) use ( $wpide_cf7_limits, $wpide_cf7_closed_message ) {
if ( 'contact-form-7' !== $tag || empty( $attr['id'] ) ) {
return $output;
}
$form = function_exists( 'wpcf7_contact_form' ) ? wpcf7_contact_form( $attr['id'] ) : null;
$id = $form ? (int) $form->id() : 0;
if ( isset( $wpide_cf7_limits[ $id ] ) && (int) get_option( 'wpide_cf7_count_' . $id, 0 ) >= $wpide_cf7_limits[ $id ] ) {
return '<p class="wpide-form-closed" role="status">' . esc_html( $wpide_cf7_closed_message ) . '</p>';
}
return $output;
}, 10, 3 );
Notes
Add form IDs and limits to the list at the top; the count is stored per form in the option wpide_cf7_count_<ID>, which you can delete to reopen 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.