Wednesday, August 29, 2012

Optgroups within Contact Form 7 in WordPress

The Contact Form 7 plugin for WordPress doesn't support select optgroups natively. I wanted to create something that would work even if the plugin is later updated, so I used jQuery.

Thank you ParkMart for starting this idea ( He ran into a bug with jQuery auto-closing the tags with his method. But this method works.

Simply create two additional options to create an optgroup.

  1. The beginning of your optgroup should be an option with the value "optgroup-XYZ" where XYZ is the label you want for your optgroup.
  2. The end of your optgroup should be an option with the value "endoptgroup".
optgroup-Title 1
item 1
item 2
item 3
optgroup-Title 2
item 4
item 5


// contact us form - change out optgroup labels
$(function() {

// search for optgroup- items
var foundin = $('option:contains("optgroup-")');
$.each(foundin, function(value) {
     var updated = $(this).val().replace("optgroup-","");

// find all following elements until endoptgroup
.wrapAll('<optgroup label="'+ updated +'"></optgroup');
// remove placeholder options



Paul said...

Hi Nathan,

Just want to say thanks ...

Works a treat!!! :-)

Nathan Markey said...

Great, glad to hear it!

Anonymous said...

Hi Nathan, may i know where should i put the code?

Nathan Markey said...

You can put it in a JavaScript script that is included on the page load on the page where the form is displayed.

Pete said...

I just installed this along with Eric Hynds jquery multi select widget

At first the jquery widget was displaying the optgroup titles and end option with check boxes, I was about to start modifying the code to disable the check boxes in the opening and closing option groups

But the problem was I was firing off the widget jquery first. And the solution was to simply have your code fire before the widget jquery to take care of the opt groups then the select widget fires styling the optgroups nicely.

Nice piece of code thanks

Dublin Dining said...
This comment has been removed by the author.
Anonymous said...

Wonderful work! Many thanks!

Rick Torres said...

Works great, thanks !

Anonymous said...

Hi Nathan!

Great work! Thanks for share!

Anonymous said...

Doesn´t work or dont know where to paste it. I tried to put in jquery.form.min.js and into the script.js, both in /wp-content/plugins/contact-form-7/includes/js/ and nothing happened.

Richelly Italo said...

Thanks, works!

Richelly Italo said...
This comment has been removed by the author.