Setting a form field from a cookie giving weird results

I am setting a Gravity form field value from a cookie (set by Google Tag Manager) using the filter below in functions.php

add_filter( 'gform_field_value_utm_campaign', 'populate_utm_campaign');
function populate_utm_campaign( $value) {
    return$_COOKIE['utm_campaign'];
}

All is working, however the values that are being populated are always from the previous session’s cookie (I’m always one session behind.)

I believe this might be due to the filter function running before Google Tag Manager gets a chance to set the new cookie.

I’m relatively new to this, so my question may need to be asked in a GTM forum, but I’m posting here in the hope someone might have had this problem before and be able to point me in the right direction.

Have a look at this plugin, I think it will help you out. I use it on a few sites with GF and it delivers as promised. A very simple and fast solution. I use the pro version.

PS - I am not an affiliate, just a user.

Scott

Much appreciated, thank you. I’ll check it out.