I've tried to search for this issue here at StackOverflow, but the answers are quite generally speaking, so I'm having some trouble with knowing how to do this exactly.
I have a Contact Form 7 form with two fields: one for email called your-email
and one for telephone called your-telephone
. I want the form to accept either one of these fields, and to invalidate when both fields are empty.
I found a snippet that doesn't do exactly this, but seems to use the right hook for it, here: https://wpquestions.com/Cross_Field_Validation_in_Contact_Form_7/10078
I transformed the code to my purpose like this and it's working halfway:
add_filter( 'wpcf7_validate', 'wpq_validate' );
function wpq_validate( $result ) {
$email = filter_input( INPUT_POST, 'your-email', FILTER_SANITIZE_STRING );
$telephone = filter_input( INPUT_POST, 'your-telephone', FILTER_SANITIZE_STRING );
$error_msg = 'One of these fields must be entered';
if( empty($email) && empty($telephone) ) {
$result['valid'] = false;
$result['reason']['your-email'] = $error_msg;
$result['reason']['your-telephone'] = $error_msg;
}
return $result;
}
By "halfway", I mean that the form is not submitted when I leave both fields empty. But it's not showing any error messages and the loading spinner of the form just spins infinitely. I'm guessing there are some calls in the code that are deprecated, since the code was posted in 2014.
So does anyone know how I should change this according to the current version of Contact Form 7?