Gravity Forms is a flexible, easy to use form plugin for WordPress. The vast list of hooks and filters allows the plugin to extended in almost any way possible.
Recently I had a client who wanted data submitted in a form to also be added to a custom database table. Gravity Forms made this task easy to accomplish.
1. Create Custom Database Table
First, we create a function to run on plugin activation,
endo_create_custom_table. By setting the function to run on plugin activation the custom table function will only run once. Inside of the function set the name of the custom table. You can prepend the default table prefix for the particular WordPress installation using
Next, set a variable
$sql with the information for the new table. In this case we are adding a column for id, entry_id, date, email, param1, and param2. These columns can be set to anything you like. In this case we need a place to store information from two unique fields of the form (param1 and param2), plus the date, entry_id of the form entry, and the email address submitted through the form.
Finally, pass the variable to the
dbDelta() function. This function examines the current table structure, compares it to the desired table structure, and either adds or modifies the table as necessary.
2. Use Gravity Forms Hook to Save Data
gform_after_submission hook, we can run a function after a form is submitted. In this case we want to save some of the data to our custom database table from step 1.
First, create a function and pass the
$form object to it so the form data can be used in the function. Next, determine which entry value to use for each piece of data you need to save. An easy way to find the correct id is to View Source on the form and find the id of the form input you want.
For example, if the id of the email input of your form is input_1_5, then the email address can be accessed with
insert method of the $wpdb object, now we take our submitted data and save it to our custom database table. Enter the name of the table, and then enter an array of values to save to table. Make sure the column name matches exactly, or none of your data will be saved.
If saving the data fails, the function won’t tell you which value caused the error. Test it with one value, and once that value saves, move on to the next one. Continue until all of the values save correctly.
Saving data into a custom database table in WordPress can be done easily with Gravity Forms. Using the hooks and filters supplied with Gravity Forms, you can manipulate and use the data any way you like.