Skip to content

Instantly share code, notes, and snippets.

@damiencarbery
Last active July 1, 2020 11:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save damiencarbery/d5b0ab443a56f2ebb12daff1637a9ded to your computer and use it in GitHub Desktop.
Save damiencarbery/d5b0ab443a56f2ebb12daff1637a9ded to your computer and use it in GitHub Desktop.
Contact Form 7 - Redirect after submission - Redirect user to new page after successful submission of a Contact Form 7 form. http://www.damiencarbery.com/2020/06/contact-form-7-redirect-after-submission/
<?php
/*
Plugin Name: Contact Form 7 - Redirect after submission
Plugin URI: http://www.damiencarbery.com/2020/06/contact-form-7-redirect-after-submission/
Description: Redirect user to new page after successful submission of a Contact Form 7 form.
Author: Damien Carbery
Version: 0.1
*/
class CF7RedirectionAfterSubmit {
private $redirection_urls; // Store form id => redirection url.
private $active_forms; // Store IDs of forms on the displayed page.
public function __construct() {
// Change these IDs and urls for your site.
$this->redirection_urls = array(
10 => 'http://mydomain.com/redirect-for-form-ten/',
18 => 'http://anotherdomain.com/thank-you-form-eighteen/', // You can redirect to another site.
);
$this->active_forms = array();
$this->init();
}
// Set up actions.
public function init() {
add_action( 'wpcf7_contact_form', array( $this, 'store_form_ids' ) );
add_action( 'wp_footer', array( $this, 'redirection_js' ) );
}
// Store IDs of forms active on the current page.
public function store_form_ids( $cfg_obj ) {
$this->active_forms[] = $cfg_obj->id();
}
// Create JavaScript code for active forms.
public function redirection_js() {
// Remove duplicate values, in case a form is used more than once on the page.
$this->active_forms = array_unique( $this->active_forms );
// Obviously only continue if there are CF7 forms on this page.
if ( count( $this->active_forms ) ) {
// Check if any of the forms have redirects.
$redirection_set = false;
foreach ( $this->active_forms as $id ) {
if ( array_key_exists( $id, $this->redirection_urls ) ) {
$redirection_set = true;
}
}
if ( $redirection_set ) {
// Print JS.
?>
<script>
document.addEventListener( 'wpcf7submit', function( event ) {
<?php
// Write out the relevant redirect for each form.
foreach ( $this->active_forms as $id ) {
if ( array_key_exists( $id, $this->redirection_urls ) ) {
?>
if ( '<?php echo $id; ?>' == event.detail.contactFormId ) {
location.replace( '<?php echo $this->redirection_urls[ $id ]; ?>' );
}
<?php
}
}
?>
}, false );
</script>
<?php
}
}
}
}
$CF7RedirectionAfterSubmit = new CF7RedirectionAfterSubmit();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment