简体   繁体   中英

Accept either one of two fields in Contact Form 7 (PHP/Wordpress)

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?

I managed to work out the code with some inspiration from more updated snippets regarding the wpcf7_validate filter. This code prevents the form from submitting and shows two error messages below each of the two fields. It's not really DRY, and I would prefer if the form showed a general error below the whole form instead of showing errors on each field. So would love some tips from anyone who knows how to do that.

function wpq_validate( $result ) {

$form  = WPCF7_Submission::get_instance();
$email = $form->get_posted_data('your-email');
$telephone = $form->get_posted_data('your-telephone');

if(  empty($email) && empty($telephone) ) {
$result->invalidate('your-email', 'Either one of these fields must be filled. Please try again.' );
$result->invalidate('your-telephone', 'Either one of these fields must be filled. Please try again.' );
} 
return $result;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM