Portfolio: Ostryweb @ Instagram.

pondělí 15. května 2017

Pass values from shortcode in Contact Form 7

I'm releasing this article because it took me a few hours to find the solution, though it is very simple. The internet is full of references to Contact Form 7 Dynamic Text Extension plugin, which is not necessary, in fact I wasn't able to achieve what I wanted with it and pure CF7 plugin was enough.

The task was to pass the values from the Wordpress template script to Contact Form 7 form. PHP template script creates the correct Contact Form 7 shortcode with generated values and the result is form with pre filled fields with these values. In my case I then used CSS styling to make the fields look like regular text, as Contact Form 7 has no function to simply output the values without creating the form fields (AFAIK).

In the Wordpress Contact Form 7 admin - create a form and add fields like this (I'm adding more then one as an example). The default:shortcode_attr parameter means that the prefilled value is expected to be passed from the shortcode. You have also other options, which can be multiple and are processed one after another until the value is passed (see this for details). I'm also adding readonly parameter as I will use the value as regular text, not real input field.

In Wordpress template I generate the form:

And to be able to pass the values to these custom variables, also this piece of code has to be added to your Wordpress template's functions.php file. You need to change the names of the fields to match both form in admin and shortcode in template script:

The resulting CF7 form will have two fields (here field-one and field-two) pre populated with the text "This can be dynamic" and "This can be also dynamic".