Use a static file to update WordPress forms with Grunt

We often rely on Contact Form 7 when implementing forms with WordPress. Sometimes a form can get quite complex with dozens of fields.

In such cases, using the regular ol› textarea in the WordPress Admin to create and/or edit those fields is not very comfortable.

To make this process more manageable, we usually build the forms using a code editor and save it as a plain .html file. (This way we can also version track all the changes with Git!)

This works well to create the forms, but we still had to copy/paste them into the editor each time we wanted to make a change. With a combination of WP-CLI and grunt-shell we found a way of updating the form automatically every time we change something in the html file.

Contact Form 7 saves the forms as post meta to the database with the key _form. So this is where we want to push our changes to.

The following code in our Grunt configuration file sets up the shell script which will update the post meta in our database.

shell: {
    updateform: {
        command: 'cat form-templates/very-complicated-form.html | wp post meta update [form-post-id] _form'

Using the cat command, we get the contents of the .html file. This is then used as input for the wp command, which updates the post meta data of the form post.

We added this task to our Grunt watch task, so whenever changes are made to our template file, the form is updated automatically without us ever touching the WP admin.

How are you handling complex forms in WordPress?