Using WordPress filters to modify Contact Form 7 Output

We at Rolling Lab like to use WordPress plugins. Using them means we have to do less coding, meaning you pay less and your projects are completed sooner. Sometimes though, plugins don’t do exactly what we want them to.

Take for example a recent occurrence we had while redeveloping the contact section on our site. We’ve always used Contact Form 7 as it has a good backend UI, and for the most part outputs what we want. Plus it’s free compared to it’s main competitor (Gravity Forms). The one problem we’ve always had with it, is that it wraps </p> tags anytime there was a carriage return in the backend editor.

Now, we had inserted two paragraphs of text at the beginning of the form, which normally would be fine. But in this instance we were attaching a float: left; & width: 50%; to .wpcf7-form p tags, meaning our forms and accompanying text were split into two columns. This looked bad. We wanted our text to be full-width, and then the form inputs to be split into two-columns.

To get around this, we used WordPress filters and regular expressions*. Below is a Gist of the code we used. As always, insert into functions.php of your theme.

I’m using two filters used by Contact Form 7, but there are others. If you’re curious to find more, open up ‘/plugins/contact-form-7/includes/classes.php’, then look for any apply_filter() functions. You can alternatively open up Terminal, cd to contact-form-7 and do a grep -R "search-terms" . search.

Once you have your filters – they’re usually appropriately named (see: wpcf7_form_elements) – attach your own filtering function using add_filter. As you can see in both examples I’ve used strip an element, or add a class to the output and then return it.

Make sure to use this approach of using WordPress filters. Don’t for a second think that you can go and edit the plugin core files itself. Never, EVER edit WordPress core or WordPress plugin files. Not only could you break some functionality (and potentially do terrible things to your site), but you also won’t be able to update your WordPress install/plugin without potentially overwriting your edits. This means no security patches. Plus, this approach is very easy, and keeps all of your edits in one file for quick and easy edits in the future.


* We use preg_replace to parse our HTML. Feel free to argue against this, but we felt this was a small enough scenario to merit this solution