Gravity Forms - Dynamic Confirmation Redirects in WordPress

Extending well-built WordPress plugins and themes is something I do almost daily. Gravity Forms is a popular form-building plugin for WordPress that I integrate and customize quite frequently. Custom form fields, form settings, and third-party integrations are common requests.

Recently, I had to find a way to handle custom, dynamic redirects on form submission.  The redirect would be dependent on query string parameters provided by an inbound affiliate link.  I was able to quickly create a solution due, in no small part, to the fact that Gravity Forms is a “well-built” plugin.1A “well-built” third-party plugin/theme means that it adheres to WordPress Coding Standards and makes APIs/hooks available to other developers for extending the base functionality, among other things.

The Challenge

To solve the challenge summarized above, the client’s original solution was to simply create separate forms for each incoming affiliate URL and set a static redirect confirmation for each of those forms.

However, that can get nasty in a hurry.  Imagine many unique affiliate links with each one requiring a separate form.   That isn’t fun for admins to manage, and it would violate a sacred tenet of good development: “DRY”2”DRY” – Don’t Repeat Yourself.  A big no-no in development or even general process efficiency. code.

Instead, it would be nice if we could have a single form that has a dynamic redirect confirmation based on the incoming URL’s query string.  We’d get bonus points for being able to define, from the admin, query string parameter keys, values, and associated redirects for each combination.

Gravity Forms Gets A Smiley For Its Hooks

As it turns out, we can create the dynamic confirmation redirects.  Gravity Forms makes available a hook named gform_confirmation that allows us to filter, or change, the default confirmation settings for a form on submission.

The gform_confirmation hook provides four arguments.  The $confirmation variable is the incoming, default redirect, $form is the current form object, $entry is the submitted form data, and $is_ajax tells us if this form is sent via AJAX.

The $confirmation variable is the one we’ll return from our filter function. If you’re familiar with the Gravity Forms form builder in the admin, you’ll know that there are three types of confirmations: text, page, and redirect. For the text type, the $confirmation variable comes to us as a string, and page and redirect come as an array. Ergo, as a redirect, we’ll need to return an array.

Putting all of this together, we can update the confirmation with a small snippet in our theme’s functions.php file.

<?php
function de_gforms_confirmation_dynamic_redirect( $confirmation, $form, $entry, $ajax ) {
    $confirmation = array( 'redirect' => 'https://redirect.com' );

    return $confirmation;
}

add_filter( 'gform_confirmation', 'de_gforms_confirmation_dynamic_redirect', 10, 4 );
?>

The code here is pretty straightforward. We’re simply overriding the confirmation settings for the form to redirect the user to “https://redirect.com”. However, this function is now attached to every Gravity Forms form submission. What if we only want to apply this change to a specific form?

<?php
function de_gforms_confirmation_dynamic_redirect( $confirmation, $form, $entry, $ajax ) {
    if ( $form['id'] == '1229' ) {
        $confirmation = array( 'redirect' => 'https://redirect.com' );
    }

    return $confirmation;
}

add_filter( 'gform_confirmation', 'de_gforms_confirmation_dynamic_redirect', 10, 4 );
?>

Above we’ve added a conditional check on the $form variable passed to our filter. Now, our filter only applies to form ID 1229. The “id” is just one form property we can check for in the object. See the documentation for a complete list of all form properties available.

Next, we can check the $entry object. We can choose to filter the confirmation based on the submitted form data:

<?php
function de_gforms_confirmation_dynamic_redirect( $confirmation, $form, $entry, $ajax ) {
    if ( $form['id'] == '1229' ) {
        if ( $entry['2'] == 'Own' ) {
            $confirmation = array( 'redirect' => 'https://redirect.com/owners' );
        } else if ( $entry['2'] == 'Lease' ) {
            $confirmation = array( 'redirect' => 'https://redirect.com/leasees' );
        } else if ( $entry['2'] == 'Rent' ) {
            $confirmation = array( 'redirect' => 'https://redirect.com/renters' );
        }
    }

    return $confirmation;
}

add_filter( 'gform_confirmation', 'de_gforms_confirmation_dynamic_redirect', 10, 4 );
?>

In this example, we have a form ID 1229 with a select/radio field for the user to select their housing type. If the user owns their home, we send them to one page, and if they rent or lease, we send them somewhere else. Fields are numbered keys in the $entry object, and there are many other values available to you with the object. See the documentation for more information.

In our last example, we’ll accomplish our original objective of redirecting a user based on a query string parameter. The parameter key is static, but there are several possible values. Using $_GET, we can get the parameter and check it in our filter.

<?php
function de_gforms_confirmation_dynamic_redirect( $confirmation, $form, $entry, $ajax ) {
    $query_string_redirects = array(
        'own' => 'https://redirect.com/owners',
        'lease' => 'https://redirect.com/leasees',
        'rent' => 'https://redirect.com/renters'
    );

    if ( $form['id'] == '1229' ) {
        if ( isset( $_GET['parameter'] ) && ! empty( $_GET['parameter'] ) && in_array( $_GET['parameter'], $query_string_redirects ) ) {
            $parameter = filter_var( $_GET['parameter'], FILTER_SANITIZE_STRING );

            $confirmation = array( 'redirect' => $query_string_redirects[$parameter] );
        }
    }

    return $confirmation;
}

add_filter( 'gform_confirmation', 'de_gforms_confirmation_dynamic_redirect', 10, 4 );
?>

A $query_string_redirects array is setup to map our expected values for $_GET['parameter']. The code then checks to ensure $_GET['parameter'] is set, has a value, and the value is one of the options in our mapping array. If those conditions are met, we sanitize the value and set the $confirmation to its associated redirect URL.

However, the parameter keys and values are statically hard-coded in our filter function.  What if the form was a user signup form on a corporate site, but the redirect sends users to a URL specific to that user’s location? Each time a new location is added, the code must be updated to accommodate the additional redirect mapping. No matter the use-case, we’d much rather control the $_GET parameter key and the possible values.

Bonus Points!

My affection for ACF is well documented, so we’ll use that. A quick “options” page could be built to create settings to handle the dynamic redirects. This gives admins control over their forms and any custom redirects.

The options page would have fields to make our entire snippet dynamic. A “form” field could select which form ID the redirects apply to. The query string key could be defined as a filed also, so instead of checking for $_GET['parameter'] we might check for $_GET['location'] or $_GET['branch'].

The last fields to define on our options page are the redirect mappings. This could easily be accomplished with a “repeater” field. Admins could then quickly add/edit/delete mappings for things like location, as in our example above. For instance, when a new location in New York is added, they could quickly add a new mapping. The mapping would require that if the $_GET['location'] parameter is set to “ny”, the associated redirect URL would be ‘https://redirect.com/locations/new-york’.

Custom Gravity Forms Setting

Another option is to add custom settings directly in the form editor on the admin side. More hook awesomeness comes by way of a gform_form_settings filter made available by Gravity Forms. With some additional code, you could use this hook to add custom settings. Even the ACF-repeater-like functionality for multiple redirect mappings could be implemented with some JavaScript.

In closing, this article should as an example of how easy, and satisfying, customizing a great WordPress plugin can be for developers. When you’re building your own custom plugins, try to think of instances where another developer may need to alter a value or trigger an action at some specific point in your code. WordPress’s apply_filters and do_action functions are relatively easy to include in your code, and they make me very happy when I see them. To me, it’s what makes a “well-built” plugin.

About

Web Developer

References

References
 1 A “well-built” third-party plugin/theme means that it adheres to WordPress Coding Standards and makes APIs/hooks available to other developers for extending the base functionality, among other things.
 2 ”DRY” – Don’t Repeat Yourself.  A big no-no in development or even general process efficiency.

27 Comments

  1. phantom

    I am working on a gravity form, and at the end of the form, I want the user to have the option to choose between two social media sites to submit their review.

    Example: “It was our pleasure to serve you. Would you take a few minutes to help others in the community by sharing your experience at one of the following sites?” Yes… No…

    If they choose “Yes”, they must get the option to choose between Google or Facebook. There is an option in the form itself to redirect the user to an URL, but I cannot find a way to make the user choose one of the 2 social media sites before they get redirected to the ones they have chosen.

    I also don’t see a conditional logic redirect option. Any ideas how i can accomplish this?

    1. David

      Phantom,
      That’s pretty much the gist of the tutorial, but your form fields are slightly different. Try this:

      <?php
      function de_gforms_confirmation_dynamic_redirect( $confirmation, $form, $entry, $ajax ) {
          if ( $form['id'] == '1229' ) {
              if ( $entry['2'] == 'Google' ) {
                  $confirmation = array( 'redirect' => 'https://www.google.com' );
              } else if ( $entry['2'] == 'Facebook' ) {
                  $confirmation = array( 'redirect' => 'https://www.facebook.com' );
              } 
          }
      
          return $confirmation;
      }
      
      add_filter( 'gform_confirmation', 'de_gforms_confirmation_dynamic_redirect', 10, 4 );
      ?>

      You’ll need to incorporate your specific form ID in place of “1229”, and you’ll need to get the $entry key that points to the Google/Facebook selection field. Finally, update the redirect URLs in the snippet to point to the appropriate destination.

    1. David

      I think given the scope and goal of this tutorial, the sample code is sufficient. There are hundreds of basic Gravity Forms snippets out there. Given that, I cover the more esoteric side of code.

    1. Kevin Allen Evans

      YOu can do this with the redirect but you would have to create a thousand forms, one for each page. It needs to somehow pass the link to the form, to just use one form for all pages.

      1. David

        Have you thought about using ACFs to have an array of redirects? Structure I’m thinking of would be select page/post then select the redirect for form on that page. In the confirmation redirect function, reference the array with the current page, and you should be able to get the redirect for that page.

  2. Scott

    Is it possible to redirect (sending query string parameters along) to an offsite URL while also (possibly in the main window, with the redirect in a new window) go to the default thank you page or thank you message? Is it possible to do a background redirect?

    It seems the GF Confirmation tool allows multiple confirmations, but I haven’t been able to get 2 different actions to work. If there’s a re-direct first, it redirects and never does the second confirmation (open Thank You page). If the page is the first confirmation, well it might be sending to the offsite URL but since no other window opens I can’t be sure.

    1. David

      You can just add a JavaScript event listener to the submission. That, in concert with the server-side redirect, should accomplish what you’re looking for.

  3. ProWP

    I am integrating a payment gateway with my GForms. How I want to make only users with successful payments will be redirected to the Thank You page?

  4. Johnson

    Hi, what if I wanted to redirect user to a certain page when user select a subscription package after submitting the form?

  5. Sam

    Thanks for the great article David. Super relevant despite being a bit old. I have a query. After form submission, we want to redirect users to a link to join whatsapp group. Whatsapp supports only 256 users so I want to change the group link after every 200 submissions. All the groups are created and links are available.

    Is there a way to accomplish this via code.

    1. David

      You could setup a global option in WP core or ACF that you rotate manually. Or, if you know/control the group link structure, you could rotate an array of them, using a stored value as the current index in use.

  6. Blake Miller

    This is awesome and fits (almost) exactly that I need. Thank you for posting. I’m a php novice… not a complete noob, but green when it comes to custom coding.

    I embed (via the template) a Gravity Form on a Custom Post Type post that automatically has a corresponding “Thank You” page sitting underneath it. I need the confirmation redirect to go to the corresponding thank you page of the parent it came from. E.g.:

    ../event/wine-tasting/register/
    would automatically redirect to:
    ../event/wine-tasting/thank-you/

    ../event/beer-tasting/register/
    ../event/beer-tasting/thank-you/

    and so on.

    So it would definitely be some sort of custom query string, but based on the URL that the form is being submitted on, not a user entry like your example. I’m just not sure how to code out the query string. (Insert that noob here 🙂

    Thank you!

  7. Phil

    Hi,

    I see the last post on this page was 2021, hope I can get an answer.

    I’m using Gravity forms webbook to send data to a 3rd party API. The form submission works, as I get a 200 status return response.

    Here is my problem, this 3rd party API has to return a URL to the user and redirect the user to the url based on this below and I don’t know how to do this?

    The process is:
    1. user fills out form and submits
    2. you send the data to our API
    3. if cpl_total or cpf_count values are > 0, redirect the user to the redirect_url value our server sends back to you

    Would this gforms_confirmation achieve this?

    Thank you much
    Phil

    1. David

      Phil,
      Yep, this could easily work Just call the API, process the response to determine the conditions you mentioned in #3, then redirect the user to the appropriate URL based on that.

  8. David Parkinson

    I have several hundred unique gravity forms and want to change the default gravity form confirmation to redirect a user to a thank-you page after submiting a form. Rather than changing the confirmation settings on each page, I thought I could do that with the first example shown above by placing the php script in my child-themes functions.php.

    Adding the script causes a fatal error and wordpress fails to load. Any idea what I’ma doing wrong. Seems straight forward.

Add Your Thoughts

Your email address will not be published. Required fields are marked *