Contact Form 7 is a popular plugin for adding forms to WordPress sites, and with a few handy snippets, you can take your forms to the next level.
Custom Validation:
Sometimes you need more than just basic form validation. With this snippet, you can add custom validation logic to your Contact Form 7 fields.
add_filter( 'wpcf7_validate', 'custom_contact_form_validation', 10, 2 );
function custom_contact_form_validation( $result, $tags ) {
$your_field_name = 'your-field-name';
// Check if your field is present in the form
if ( isset( $_POST[$your_field_name] ) ) {
$your_field_value = sanitize_text_field( $_POST[$your_field_name] );
// Add your custom validation logic here
if ( empty( $your_field_value ) ) {
$result->invalidate( $tags[$your_field_name], 'Please enter a value for your field.' );
}
}
return $result;
}Remove <p> Tag:
Sometimes Contact Form 7 automatically wraps form elements in <p> tags, which might not be what you want. Use this snippet to disable this behavior.
add_filter( 'wpcf7_autop_or_not', '__return_false' );
Change HTML Tag for Submit Button:
Want to change the HTML tag for your form’s submit button? No problem! This snippet allows you to replace the <input> tag <button>with a tag.
add_filter( 'wpcf7_form_elements', 'my_custom_button' );
function my_custom_button( $form ) {
$form = str_replace( 'input type="submit"', 'button type="submit"', $form );
$form = str_replace( '</input>', '</button>', $form );
return $form;
}By using these snippets, you can customize your Contact Form 7 forms to better suit your website’s needs. Whether it’s improving validation, adjusting HTML tags, or fine-tuning elements, these snippets provide you with the flexibility to create forms that work seamlessly with your WordPress site.
