How to pre-fill fields from values in a URL query string

Created by Phil Kurth, Modified on Fri, 01 Jul 2022 at 09:29 AM by Phil Kurth

If you need to use values from the URL query string — e.g; example.com/page?my-custom-param=some-value — you may do so using the af/field/prefill_value filter

add_filter( 'af/field/prefill_value', function ( $value, $field, $form, $args ) {
  // If we need to run this only on a specific form, check for the form key.
  if ( $form['key'] !== 'YOUR_FORM_KEY_HERE' ) {
    return $value;
  }

  // Check the for the desired field and if the URL contains the expected parameter, use it.
  if ( $field['name'] === 'YOUR_FIELD_NAME_HERE' && isset( $_GET['YOUR_QUERY_VAR_HERE'] ) ) {
    $value = $_GET['YOUR_QUERY_VAR_HERE'];
  }
  
  return $value;
}, 10, 4 );

Whilst the above example works for most field types, some field types will require special formatting:

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select atleast one of the reasons

Feedback sent

We appreciate your effort and will try to fix the article