WooCommerce and Gravity Forms
Gravity Forms product Add-ons is a great WooCommerce plugin, giving one ability to specify custom product fields per each product. It gives the ability of extending products with certain custom fields, which is unavailable by default.
It’s most commonly used with:
- product specific labels (like a nickname on a T-shirt)
- product specific data (like event or a course date)
- customized logo image
This plugin extends basic WooCommerce shop with nearly unlimited amount of options ending up in an absolute, service focused solution.
I personally used this add-on in three cases:
- WooCommerce based interactive tour selling for hotels
- Paid events using date picker to specify the most suitable date from a number of dates
- Extra product labels (obvious)
This tutorial assumes that you have downloaded and properly installed these four plugins (however it can be used without the WooCommerce plugins as well):
With Advanced Custom fields I’m going to create several (or one :p) product custom fields, which will then serve as a selection for fields on the single product page. This will give the visitor a set of options to choose from.
Let’s go ahead and create a custom datepicker field via ACF:
Now let’s go ahead and create a sample, one field (simple input should be enough) form with GF
We’ll need to store the Gravity Forms form id and add a custom field classname to identify the field later on in the future
Finally let’s assign the form to the WooCommerce product
The coding part
Now, let’s get to the code. I’m not going to follow any coding patterns (plugins vs functions.php) – it’s up to you. I want to demonstrate the code itself, so you’ll take the full responsibility on how to code that. However it’d be a wise idea to check if these plugins were active.
First, let’s overwrite the Gravity Forms Front end facing HTML of the input field
This function overwrites the form input Front End part. We should endup with the following looks:
We’ve already go the Front End, but now we’ll need to store the variable somewhere. This has to be done due to two important cases:
- field validation in case of required fields
- passing variable data along the pagination
Let’s create two hooks, which are connected to the form id:
These little fellas should assist us in form validation (in case the date wasn’t in the right format) and gives us the ability of changing the actual output. In the current solution it doesn’t matter that much. However in would become extermely useful in case of the repeater field. One’d have to map the multiple fields into one input value.
Now let’s make sure that we actually use the ACF field at all, let’s limit, the datepicker picks to one specific date:
Assuming everything went well, the end, checkout / cart / order result should look like that:
You can get the full source code from the github: https://gist.github.com/gicolek/9347980