Steps to Add JavaScript for Redirect in WordPress for Contact Form 7 Plugin

Steps to Add JavaScript for Redirect After Contact Form Submission in WordPress

If the redirect after submitting a Contact Form 7 form doesn’t work using the plugin settings, you can add the JavaScript directly to your functions.php file.

Steps to Add JavaScript in functions.php for Redirect:

  1. Access functions.php:
    • Go to your WordPress Dashboard.
    • Navigate to Appearance > Theme Editor.
    • Find and click on functions.php (Theme Functions) on the right side.
  2. Add the JavaScript Code:

    At the end of the functions.php file, add the following code:

    
    function redirect_after_contact_form_submission() {
        ?>
        <script>
        document.addEventListener( 'wpcf7mailsent', function( event ) {
            window.location.href = 'http://yourwebsite.com/thank-you'; // Replace with your Thank You page URL
        }, false );
        </script>
        <?php
    }
    add_action( 'wp_footer', 'redirect_after_contact_form_submission' );
                

    Explanation:

    • The function redirect_after_contact_form_submission adds the JavaScript to the footer of your site.
    • The event wpcf7mailsent triggers after a successful form submission.
    • The JavaScript code will redirect the user to the specified “Thank You” page URL.
  3. Save the Changes: After adding the code, click Update File to save the changes to functions.php.
  4. Test the Redirect: Go to the page where your Contact Form is located, fill out and submit the form. You should be redirected to the “Thank You” page after submission.

Why This Works:

By hooking the JavaScript into the wp_footer action, the script is guaranteed to load on every page where the footer is used, ensuring the redirect occurs after form submission.

Caution:

  • Backup your functions.php file before making any changes to avoid errors that could affect your site.
  • If you are using a child theme, it is best to add the code to the child theme’s functions.php to avoid losing changes when the theme is updated.