Dynamically populate a Contact Form 7 dropdown list (or any other input field)

With Contact Form 7 the normal way to create a drop down list, looks like this:

[select upcoming-gigs "MAY 07 - NEW ORLEANS, LA" "MAY 09 - AUSTIN, TX" "MAY 12 - HOUSTON, TX"]

That’s all very nice, but what if this information tends to change often? You probably have a data source already, be it a web API, an excel sheet, or a simple text file.

Wouldn’t it be nice to write something like this, and have the options be filled dynamically? :

[select upcoming-gigs data:gigs]

Well, in fact, you can. This is actually built-in to Contact Form 7 by default. And we can achieve the result with some really simple PHP, using the wpcf7_form_tag_data_option action hook. I failed to find any good documentation about this powerful feature. That’s why I wrote this post.

OK, so the first part is done. Our form is ready, and it looks like this:

<label>
  <strong>Your name</strong>
  [text your-name]
</label>
<label>
  <strong>Choose your gig</strong>
  [select upcoming-gigs data:gigs]
</label>
[submit]

Now, for the data:gigs part. How do we get this replaced with the actual gig dates?

For simplicity, let’s assume we already have a PHP array of dates available. (in the real world, you would generate this array from an external source.)

$gigs = array(
  "MAY 07 - NEW ORLEANS, LA",
  "MAY 09 - AUSTIN, TX",
  "MAY 12 - HOUSTON, TX"
);

Next, add this code in your theme’s functions.php file

add_filter('wpcf7_form_tag_data_option', function($n, $options, $args) {
  if (in_array('gigs', $options)){
    $gigs = array(
      "MAY 07 - NEW ORLEANS, LA",
      "MAY 09 - AUSTIN, TX",
      "MAY 12 - HOUSTON, TX"
    );
    return $gigs;
  }
  return $n;
}, 10, 3);

And voila! Here’s the completed form in action:

Your name

Choose your gig

Note: there’s also a plugin called Listo written by Takayuki Miyoshi, that uses this approach to pre-populate some common lists, like countries, currencies and time-zones. But now you know how you can add your own custom lists to CF7 too.