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:
- 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.
- Add the JavaScript Code:
At the end of the
functions.phpfile, 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_submissionadds the JavaScript to the footer of your site. - The event
wpcf7mailsenttriggers after a successful form submission. - The JavaScript code will redirect the user to the specified “Thank You” page URL.
- The function
- Save the Changes: After adding the code, click Update File to save the changes to
functions.php. - 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.phpfile 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.phpto avoid losing changes when the theme is updated.
