| |

Capturing gclid in WordPress

This post is something I used Gemini to write and implement. You can actually just use the chat above to get your own custom version of it. Copy the below question with your form and it will spit out the answer.

How do I capture Gclids in WordPress contact form? And send back back to google for conversions via Google Sheets?

Never Lose Lead Data: Capture URL Parameters in Contact Form 7

Ever wonder exactly which marketing campaign, referral link, or Google Ad click led to a contact form submission on your WordPress site? By default, valuable tracking information stored in URL parameters (like gclid, utm_source, ref, etc.) gets lost when a user fills out and submits a form. This makes it hard to measure your marketing ROI accurately.

But don’t worry! There’s a straightforward way to capture these parameters when a visitor first lands on your site and include them automatically in your Contact Form 7 email notifications. This involves adding a couple of simple code snippets and making minor adjustments to your form.

In this guide, we’ll walk you through step-by-step how to capture the Google Click ID (gclid) and the entire original query string from the landing page URL, store them temporarily, and send them along with your Contact Form 7 submissions.

What You’ll Need

  • A WordPress website.
  • The Contact Form 7 plugin installed and activated.
  • The Code Snippets plugin installed and activated (or another method to add JavaScript to your site’s header and footer).
  • About 15-20 minutes.

The Strategy: Capture, Store, Populate, Send

Here’s the plan:

  1. Capture: When a visitor lands on any page of your site, a small script will grab any URL parameters present (specifically looking for gclid and also the complete parameter string).
  2. Store: These captured values will be saved in the visitor’s browser as cookies. Cookies help “remember” this information even if the visitor navigates to other pages before submitting the form.
  3. Prepare CF7: We’ll add hidden fields to your Contact Form 7 form to hold the captured data.
  4. Populate: When the form page loads, another script will read the stored cookies and automatically fill in the hidden fields.
  5. Send: When the form is submitted, Contact Form 7 will include the data from these (now populated) hidden fields in the email notification.

Step 1: Add Hidden Fields to Your Contact Form 7

First, we need to tell Contact Form 7 where to store the data we capture. We use hidden fields so they don’t clutter the form for the user.

  1. In your WordPress dashboard, go to Contact -> Contact Forms.
  2. Edit the form you want to track parameters for.
  3. Switch to the Form tab.
  4. Paste the following two lines somewhere within the form structure (e.g., just before the [submit] button). Their exact position doesn’t matter visually as they are hidden.

HTML

[hidden gclid id:gclid-field]
[hidden landing_query id:query-string-field]
  • [hidden gclid ...] creates a hidden input field named gclid. We’ll use this name later in the email template.
  • id:gclid-field gives this field a unique HTML ID so our script can easily find it.
  • The landing_query field will store the entire original query string (e.g., ?gclid=123&utm_source=abc).
  1. Save the contact form.

Step 2: Add the Tracking Code Snippets

Now, we’ll add the JavaScript code that does the capturing and populating. We’ll use the Code Snippets plugin for this. We need two separate snippets: one runs immediately in the header to capture data from the current URL, and one runs later in the footer to populate the form once it exists.

Snippet 1: Capture Parameters & Set Cookies (Header)

This first snippet runs on every page load. It checks the current URL for gclid and the full query string and saves them into cookies.

  1. Go to Snippets -> Add New.
  2. Give it a clear title, like CF7 Tracking - Set Cookies (Header).
  3. Paste the following code into the main code area:

HTML

<script type="text/javascript" id="cf7-param-setter-clean">
(function() {
    'use strict';
    // Helper function to set cookies
    function setCookie(name, value, days) {
        let expires = "";
        if (days) {
            const date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toUTCString();
        }
        // Set cookie site-wide with SameSite attribute
        document.cookie = name + "=" + (value || "") + expires + "; path=/; SameSite=Lax";
    }

    // --- Main Logic: Capture parameters and set cookies ---
    try {
        const params = new URLSearchParams(window.location.search);
        const gclid = params.get('gclid');
        const queryString = window.location.search; // Includes '?'

        // Set cookies if parameters are found in the current URL
        if (gclid) {
            setCookie('gclid_landing', gclid, 30); // Store gclid for 30 days
        }
        // Check if query string exists and has content beyond '?'
        if (queryString && queryString.length > 1) {
             // Encode to safely store special characters in the cookie
             const encodedQueryString = encodeURIComponent(queryString);
             setCookie('landing_query_string', encodedQueryString, 30); // Store query string for 30 days
        }
    } catch (e) {
        // Log errors if they occur during parameter capture or cookie setting
        console.error("CF7 Header Snippet Error:", e);
    }
})();
</script>
  1. Configure the Snippet Settings:
    • Make sure the type selected allows direct HTML/JavaScript input.
    • Location/Placement/Hook: Choose Header (or equivalent option to place before </head>).
    • Scope: Select “Run snippet everywhere” or “Only run in site front-end”.
  2. Click Save Changes and Activate.

Snippet 2: Read Cookies & Populate Form (Footer)

This second snippet runs after the page’s HTML has loaded. It reads the cookies set by the first snippet (or from a previous visit) and fills in the hidden fields in your Contact Form 7 form.

  1. Go to Snippets -> Add New.
  2. Give it a clear title, like CF7 Tracking - Populate Fields (Footer).
  3. Paste the following code into the main code area:

HTML

<script type="text/javascript" id="cf7-field-populator-clean">
(function() {
    'use strict';
    // Helper function to read a specific cookie
    function getCookie(name) {
        const nameEQ = name + "=";
        const ca = document.cookie.split(';');
        for(let i = 0; i < ca.length; i++) {
            let c = ca[i];
            while (c.charAt(0) === ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) === 0) {
                return c.substring(nameEQ.length, c.length);
            }
        }
        return null;
    }

    // --- Main Logic: Read cookies and populate fields after DOM is ready ---
    document.addEventListener('DOMContentLoaded', function() {
        try {
            // Get values from cookies
            const gclidCookieValue = getCookie('gclid_landing');
            const queryStringCookieValueEncoded = getCookie('landing_query_string');

            // Find the target hidden fields in the CF7 form using their IDs
            const gclidField = document.getElementById('gclid-field');
            const queryStringField = document.getElementById('query-string-field');

            // Populate the gclid field if it exists and the cookie was found
            if (gclidField && gclidCookieValue) {
                gclidField.value = gclidCookieValue;
            }

            // Populate the query string field if it exists and the cookie was found
            if (queryStringField && queryStringCookieValueEncoded) {
                // Decode the value retrieved from the cookie
                const decodedQueryString = decodeURIComponent(queryStringCookieValueEncoded);
                queryStringField.value = decodedQueryString;
            }

            // --- Fallback Logic ---
            // If fields are still empty (e.g., form is on first landing page visit),
            // try populating directly from the current URL's parameters.
            const currentParams = new URLSearchParams(window.location.search);
            const currentGclid = currentParams.get('gclid');
            const currentQueryString = window.location.search;

            if (gclidField && !gclidField.value && currentGclid) {
                 gclidField.value = currentGclid;
            }
            if (queryStringField && !queryStringField.value && currentQueryString && currentQueryString.length > 1) {
                 queryStringField.value = currentQueryString;
            }

        } catch (e) {
             // Log errors if they occur during field population
            console.error("CF7 Footer Snippet Error:", e);
        }
    });
})();
</script>
  1. Configure the Snippet Settings:
    • Make sure the type selected allows direct HTML/JavaScript input.
    • Location/Placement/Hook: Choose Footer (or equivalent option to place before </body>).
    • Scope: Select “Run snippet everywhere” or “Only run in site front-end”.
  2. Click Save Changes and Activate.

Step 3: Configure Your Contact Form 7 Email

The final step is to tell Contact Form 7 to include the data from our hidden fields in the email notifications you receive.

  1. Go back to editing your Contact Form (Contact -> Contact Forms -> Edit your form).
  2. Switch to the Mail tab.
  3. In the Message body section, add the following tags wherever you want the information to appear. Use the names of the hidden fields we created in Step 1 (wrapped in square brackets): GCLID: [gclid]Landing URL Parameters: [landing_query] You can customize the labels (like “GCLID:”) to whatever makes sense to you.
  4. Save the contact form.

Testing Your Setup

It’s crucial to test this thoroughly to make sure it’s working as expected:

  1. Clear Caches: Clear your browser cache completely. Also clear any WordPress caching plugins (like WP Rocket, Litespeed Cache, etc.) and server-side caches if applicable.
  2. Clear Cookies: Open your browser’s Developer Tools (usually F12), go to the “Application” (Chrome) or “Storage” (Firefox) tab, find Cookies for your site, and delete any existing gclid_landing or landing_query_string cookies.
  3. Visit with Parameters: Open a new browser tab and visit a page on your site with test parameters. Use gclid spelled correctly. Example: https://yoursite.com/your-landing-page/?gclid=TestGCLID_ABC123&utm_source=test_campaign
  4. Check Cookies: In Developer Tools -> Application/Storage -> Cookies, verify that gclid_landing (value: TestGCLID_ABC123) and landing_query_string (value: encoded ?gclid=...) cookies have been created.
  5. Navigate to Form: Go to the page containing your Contact Form 7.
  6. Inspect Hidden Fields: Before submitting, right-click the form -> “Inspect” or “Inspect Element”. Find the hidden fields (id="gclid-field" and id="query-string-field"). Check their value attribute in the HTML code. It should match the data from your test URL.
  7. Submit Form: Fill out the form fields and submit it.
  8. Check Email: Check the email notification you receive. It should now contain the GCLID: and Landing URL Parameters: lines with the captured data.

Troubleshooting Common Issues

If it’s not working, check these common culprits:

  • Caching: Aggressive caching is the most frequent issue. Ensure all relevant caches are cleared after making changes.
  • Parameter Typos: Double-check you are using gclid (not glcid or similar) in your test URLs and ad campaigns.
  • Snippet Not Active/Incorrect Location: Ensure both snippets are active in the Code Snippets plugin and set to the correct location (Header/Footer) and scope (Front-End).
  • Incorrect Field IDs: Verify the IDs in the JavaScript (getElementById('gclid-field'), getElementById('query-string-field')) exactly match the IDs in your CF7 form shortcodes (id:gclid-field, id:query-string-field).
  • Incorrect Mail Tags: Make sure the tags in the CF7 Mail tab exactly match the names of the hidden fields ([gclid], [landing_query]).
  • Plugin/Theme Conflicts: Temporarily switch to a default theme and disable other plugins (except CF7 and Code Snippets) to rule out conflicts.

Conclusion

Capturing URL parameters like gclid and the full referring query string provides invaluable context about your leads. By adding these simple scripts and configuring Contact Form 7 correctly, you can stop losing this data and gain much better insights into your marketing efforts directly within your form submission emails. Happy tracking!

Disclaimer: This guide involves adding custom code to your website. While tested, please ensure you have backups and test thoroughly on a staging site if possible before implementing on a live site.

If it doesn’t work, you can just go to Gemini or ChatGPT, and it will just tell you how to do it. This is the type of stuff an LLM can spit out without breaking a sweat.

How to upload to Ads is another story. That’s something that an LLM can tell you quite easily too.


Similar Posts

Leave a Reply

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