Contact Form 7 – place GET, POST, SERVER, COOKIE, SESSION etc variables into fields

April 16, 2014 | Plugins, Time Savers, Tutorials, Wordpress | 16 comments

As part of a job I am doing to extend a Contact Form 7 implementation and to pay additional homage to the plugin itself I would like to show you how to get PHP environment variables into your fields. Until now I have found myself writing complex and frankly undocumentable (through a combination of lack of time and shame at my hacky approach!) snippets to get custom data into my clients’ contact forms.

I had a similar job today whereby I had to get a $_COOKIE value into a hidden input field and also a custom PHP generated string which isn’t possible out of the box with Contact Form 7. I found the ‘Contact Form 7 Dynamic Text Extension‘ plugin after a bit of searching and although it didn’t do exactly what I wanted I sussed that it supports shortcodes. So rather than having to code a custom CF7 solution of my own I simply had to write a couple of shortcode handlers.. simples!

Out of the box you can to GET and POST with a few others. I wanted COOKIE and another of my own. The following code you can put into your theme functions.php file and in conjunction with the code for CF7 below that to generate the hidden field you can have any data prefilled into a CF7 form in minutes.

Example – Cookie

This is more or less a carbon copy of the plugin author’s own GET/POST code. I would have used a slightly more compact approach but it didn’t make sense to be different for the sake of it for the sake of my vanity. This is the code for your functions.php file:

function sb_cf7_cookie($atts){
    extract(shortcode_atts(array(
        'key' => -1,
    ), $atts));

    if($key == -1) return '';
    $val = '';

    if( isset( $_COOKIE[$key] ) ){
        $val = $_COOKIE[$key];
    }

    return $val;
}
add_shortcode('SB_CF7_COOKIE', 'sb_cf7_cookie');

The code to add this to your CF7 form is as follows:

[dynamichidden field-name "SB_CF7_COOKIE key='COOKIE_NAME'"]

Where field-name is the name of the field (go figure!) which you would use in the notification email and user email if necessary like this: [field-name]. The COOKIE_NAME part is referencing $_COOKIE[‘COOKIE_NAME’] or, for clarity, just a cookie called COOKIE_NAME.

Example 2 – PHP Logic

I won’t explain this one so much but essentially the shortcode can do whatever you need it to.. You don’t even need to pass the shortcode anything if you are going to rely on the page environment. The following is an extract taken from a contact form which was ONLY ever used on WP taxonomy pages for WooCommerce (product categories) and is designed to return the category name in a field:

function sb_cf7_catname(){
    $cat_id = get_queried_object_id(); //get category id
    $cat = get_term($cat_id, 'product_cat');  //get category object
    $val = $cat->name; //get category name

    return $val;
}
add_shortcode('SB_CF7_CATNAME', 'sb_cf7_catname');

Notice this time we don’t look for a shortcode argument in $atts and use the page object ID to work from. Because we require no shortcode arguments then the CF7 declaration is simpler as follows:

[dynamictext field-name "SB_CF7_CATNAME"]

Hopefully you will find it useful. Do let me know if you want to write a custom shortcode for CF7 (or even just a custom shortcode) and can’t get it right. I am always willing to help…

A Donate Button!

16 Comments

  1. Yvonne

    I add a contact form in woocommerce, single-product page, is it possible to show product name automatically?

    Reply
  2. Yvonne

    What I write: but not work

    function cf7_product_title(){

    $product_name = get_the_title();
    $val = $product_name;

    return $val;
    }
    add_shortcode(‘CF7_PRODUCT_TITLE’, ‘cf7_product_title’);

    And insert,
    [dynamictext* dynamictext-343 “cf7_product_title”]

    Reply
    • Sean Barton

      No problem Yvonne, you have the right idea. WP Shortcodes are case sensitive I believe so the CF7 declaration would be CF7_PRODUCT_TITLE not cf7_product_title

      Otherwise you could try the following instead of get_the_title();

      global $post;
      $val = $post->post_title;

      ta
      S

      Reply
      • Yvonne

        worked with CF7_PRODUCT_TITLE

        Many tks

        Reply
  3. Gordon

    worked with get cookie, tks Sean barton

    Reply
  4. Mitch

    Just what I needed.

    Thank you, Sean!

    Reply
  5. Jaime

    Hi there!

    Quick question: If I want to get a variable from the URL (Lets call it nickname) and I want that variable to be considered within the Cookie, How would we do that?

    Ex:

    http://www.anysite.com/?nickname=bigbird

    If the user starts browsing the web and comes back to the form, how do I set u the code above to store the “nickname” variable within the cookie, so that later on the dynamic field captures it?

    Because the part of the hidden field would be something like:

    [dynamichidden field-nickname “SB_CF7_COOKIE key=’COOKIE_nickname”]

    But how do I configure the prior step?

    Thanks,

    Jaime

    Reply
    • Sean Barton

      Hi Jaime,

      No problem.. this is simple enough.

      Add something like this to your theme functions.php file:

      < ?php if (isset($_GET['nickname'])) { setcookie('COOKIE_nickname', $_GET['nickname'], (86400*30)); } ?>

      The code is off the top of my head so might need some tinkering but essentially when nickname is in the URL it will set a cookie to be picked up in your form. It will store the cookie for 30 days. You can change the 30 to whatever you want in days.

      ta
      S

      Reply
      • Jaime

        THANK YOU VERY MUCH!! I´ll try and keep ypu posted. If I get it right, I´ll post what I did, and a little explanation.

        Thanks again!!

        Reply
  6. Jaime

    Hi agian,

    I posted the code within the functions php. To be precise, i copied

    if (isset($_GET[‘nickname’])) {
    setcookie(‘COOKIE_nickname’, $_GET[‘nickname’], (86400*30));
    }

    within the content, at eh very en, right before ?>

    To see if the code was working i tried http://www.mysite.com/?nickname=bigbird and then lookd with Firebug, the Chrome extension, the data within the cookie. The bigbird is not there at all.

    I think i did copy the correct code within the correct funtions.php file, but I might have done it wrong.

    any ideas on how to debug if I´m inserting the code correctly? Might I be missing something in the inserted code?

    Thanks

    Reply
    • Sean Barton

      Try putting it at the top of the functions.php file. Something in the file might be causing the headers to be sent and therefore the cookie would fail. Also does your host allow cookies. Maybe try changing from cookie to session which is not subject to headers being sent albeit with a shorter life than a cookie.

      Reply
      • Jaime

        Not working…

        I´ll make and backup and request you a quotation for this project.

        Thanks,

        Jaime

        Reply
        • Sean Barton

          Thanks Jaime, we have completed work together and your issue is resolved.

          Thanks!

          Reply
          • Jaime

            Sure was! quick, right price and thorough debugging. Great work. Thanks a lot.

  7. Steve

    Hi, how would adapt your code to access an array stored as a session variable?
    Thanks

    Reply
  8. indiaxp

    Nice post thank you for sharing.

    Reply

Leave a Reply

Divi United

About this site and Sean Barton

Picture of Sean
Sean Barton is a Freelance PHP Website Developer in Crewe, Cheshire. He is a Wordpress and CMS/Framework specialist.
This site was set up in 2008 as a tutorial and scripting resource for the PHP language and Wordpress.
Find out more about Sean on the About Me page or use the Hire Me page to get in touch. For more information about Sean's work take a look at the Portfolio

Our Services

  • Wordpress plugin/theme development
  • Divi specialist
  • Ecommerce (Woocommerce, WPSC, Shopify, Magento)
  • PSD to Wordpress theme conversion (Responsive)
  • Website design work (Banners, Logos, Full Site, etc)
  • Website analysis (security, usability, SEO)
  • API Integrations (InfusionSoft, SalesForce, Ontraport, Customer Thermometer, etc..)
  • Wordpress consultancy & expert advice
  • Crisis support
  • Website hosting

The main services offered are Wordpress based although we do a great deal of technical programming for bespoke systems. From troubleshooting, extending frameworks, finding bugs to writing them from scratch.

Find out more by looking through our past projects or get a quote.

Be the first to hear about new products/updates!

This is a mailing list for those people interested in being told when we release a new product (Divi plugin or Theme).

We shall also use this list to let you know about product updates and releases.

You have Successfully Subscribed!