How to Auto-Populate Fields Using URL Parameters

Auto-populating form fields using URL parameters is a powerful technique for improving user experience, boosting conversions, and integrating with marketing campaigns, CRMs, or referral systems.

What are URL Parameters?

URL parameters (query strings) are values passed in the URL after a ?.

https://example.com/form?name=John&email=john@example.com

We can extract name and email and insert them into form fields on the page.

To Auto-Populate Fields Using URL Parameters Use Below Code

JavaScript-Based Field Auto-Population

Here’s a custom JavaScript snippet you can add in your theme’s footer, or enqueue via a plugin or theme file.

Below code is regular JavaScript code it will work with all forms.

Supports input types: textemailhiddenselecttextarea

<script>
document.addEventListener("DOMContentLoaded", function () {
    const urlParams = new URLSearchParams(window.location.search);

    // Loop through all params and populate matching fields
    urlParams.forEach((value, key) => {
        let field = document.querySelector(`[name="${key}"]`);

        if (field) {
            const tagName = field.tagName.toLowerCase();

            if (tagName === "input" || tagName === "textarea") {
                field.value = value;
            } else if (tagName === "select") {
                Array.from(field.options).forEach(option => {
                    if (option.value === value) {
                        option.selected = true;
                    }
                });
            }
        }
    });
});
</script>

This code will:

  • Grab the value from URL and append values into input and selectbox using JavaScript.

Pre-Populate WooCommerce Checkout Fields

Add code to your child theme’s functions.php file or via a plugin that allows custom functions to be added, such as the Code snippets plugin. Avoid adding custom code directly to your parent theme’s functions.php file as this will be wiped entirely when you update the theme.

add_filter('woocommerce_checkout_fields', 'auto_populate_checkout_fields_from_url');
function auto_populate_checkout_fields_from_url($fields) {
    if (isset($_GET['billing_email'])) {
        $fields['billing']['billing_email']['default'] = sanitize_email($_GET['billing_email']);
    }
    if (isset($_GET['billing_first_name'])) {
        $fields['billing']['billing_first_name']['default'] = sanitize_text_field($_GET['billing_first_name']);
    }
    return $fields;
}
https://yourdomain.com/checkout?billing_first_name=John&billing_email=john@example.com

This code will:

  • Grab the Value from URL and pass the sanitize value to field using action filter hook

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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