0

I have used the following code to successfully redirect a form to an URL after submission using contact form 7.

<add_action( 'wp_footer', 'redirect_cf7' );

function redirect_cf7() {
?>
<script type="text/javascript">
document.addEventListener( 'wpcf7mailsent', function( event ) {
   if ( '947' == event.detail.contactFormId ) { // Sends sumissions on form 947 to the first thank you page
    location = 'https://www.example.com/thank-you-1/';
    } else if ( '1070' == event.detail.contactFormId ) { // Sends submissions on form 1070 to the second thank you page
        location = 'https://www.example.com/thank-you-2/';
    } else { // Sends submissions on all unaccounted for forms to the third thank you page
        location = 'https://www.example.com/thank-you-3/';
    }
}, false );
</script>
<?php
} 

Can this be modified to redirect once a certain field contains a certain value (for example [Post-Code] Contains KA7) and another field contains a value (for example [Bedrooms] == 1) ?

Thanks in advance

Andy

0

Yes, you should be able access the form fields and field values with event.detail.inputs in addEventListener on wpcf7mailsent. You can then use the field values in the conditional statements and add the redirects you need. There's a simple code sample in the plugin doumentation, https://contactform7.com/dom-events/, for looping the fields.

EDIT Here's a code example,

document.addEventListener( 'wpcf7mailsent', function( event ) {

  var inputs = event.detail.inputs,
      inputCount = inputs.length,
      firstCondition,
      secondCondition;

  for ( var i = 0; i < inputCount; i++ ) {
    if ( 'first-condition-field' == inputs[i].name ) {
      firstCondition = inputs[i].value
    } else if ( 'second-condition-field' == inputs[i].name ) {
      secondCondition = inputs[i].value
    }
  }

  if ( 'foo' == firstCondition && 'bar' == secondCondition ) {
    location = 'https://www.example.com/thank-you-1/';
  } else if ( 'bar' == firstCondition && 'baz' == secondCondition ) {
    location = 'https://www.example.com/thank-you-2/';
  }

}, false );
  • But i am looking at using 2 fields to determine an out come so would i still use the following? – Andy Strachan Mar 19 at 14:52
  • document.addEventListener( 'wpcf7submit', function( event ) { var inputs = event.detail.inputs; for ( var i = 0; i < inputs.length; i++ ) { if ( 'your-name' == inputs[i].name ) { alert( inputs[i].value ); break; } } }, false ); – Andy Strachan Mar 19 at 14:52
  • Something like that. I added a code example to my answer. – Antti Koskinen Mar 19 at 14:57
  • Amazing Antti, thanks you for this, i will give this a go. – Andy Strachan Mar 19 at 16:36
  • Would i put this into functions.php in contact form 7 plugin? – Andy Strachan Mar 19 at 17:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.