May 3, 2023: Added support for tracking "inventory" on currency-formatted Number fields.
November 11, 2012: Fixed issue where database prefix was not applied via $wpdb-<prefix.
Stop! There's a better way.
This snippet is available as a plugin with Gravity Perks, a suite of over 47 premium Gravity Forms plugins!
Overview
Gravity Forms does not support the concept of inventory out of the box. This snippet provides an easy method for setting up simple, one-off inventory limits on a per field basis.
Using the Snippet
Prerequisites
Confirm that you have Gravity Forms installed and activated and that youâve installed the snippet.
Add a Product Field
With the snippet installed, add a Product field to your form. Note the Product field’s ID.
Update Snippet with Parameters
Update the form_id
and field_id
in the snippet to match your Form ID and Field ID. Depending on the way your form is set up, you’ll need to format the Field IDs differently:
- If your form uses a separate Quantity field for the Product’s quantity, set the
field_id
to the Quantity field’s ID. - If your Product uses the built-in quantity sub-field, set the field ID to your Product ID and add
.3
to the end.
new GW_Inventory( array(
'form_id' => 123,
'field_id' => 4.3,
'stock_qty' => 20,
) );
Custom Stock Level Messages
Better Inventory includes default “out of stock” and “not enough stock” messages. These messages can be customized using the out_of_stock_message
and not_enough_stock_message
parameters.
new GW_Inventory( array(
'form_id' => 123,
'field_id' => 4.3,
'stock_qty' => 20,
'out_of_stock_message' => 'Sorry, there are no more tickets!',
'not_enough_stock_message' => 'You ordered %1$s tickets. There are only %2$s tickets left.',
) );
Out of Stock
The out_of_stock_message
is displayed when the product limit has been reached. You can get fancy with this and add HTML. Be sure to escape any double quotes with a backslash. Here’s an advanced example:
'out_of_stock_message' = '<div style="border: 1px solid #e6db55; background-color: #FFFFE0; padding: 10px;">Sorry, this show is sold out.</div>'
Not Enough Stock
The not_enough_stock_message
is displayed on the field if the limit has not been reached, but the user’s requested quantity would exceed the product limit.
Parameters
form_id (integer) (required)
The ID of the form you are working with.
field_id (integer|float) (required)
The ID of your product or quantity field. If using a Single Product field, specify the quantity input ID, which will always be
{field ID}.3
. If using a separate Quantity field, simply specify the field ID.stock_qty (integer) (required)
The number of this item you have available.
out_of_stock_message (string) (optional)
The message which should be displayed to users when the product limit has been reached.
not_enough_stock_message (string) (optional)
The message which should be displayed on the field if the limit has not been reached, but the user’s requested quantity would exceed the product limit.
approved_payments_only (boolean) (optional)
Indicate whether all submissions for this field should be counted against the limit or only submissions with an approved payment.
hide_form (boolean) (optional)
By default this snippet will only hide the field when the limit has been reached. If you would rather hide the entire form, set this to
true
.enable_notifications (boolean) (optional)
Enable the ability to create notifications that are sent when the stock of a product (or any configured field) has been exhausted
Shortcodes
Remaining
Show the quantity remaining for the specified input and limit.[gravityforms action="remaining" id="1" input_id="2.3" limit="50"]
Sum
Show the current sum of quantities ordered for this field across all entries.[gravityforms action="sum" id="1" input_id="2.3"]
Taking It Further
Approved Payments
By default, all submissions are counted against the stock quantity. Use the approved_payments_only
parameter to indicate that only submissions with an approved payment should be counted. You’ll want to be careful here when using PayPal Standard due to the delay between the form submission and the payment being approved. It could lead to users exceeding the limit.
new GW_Inventory( array(
'form_id' => 123,
'field_id' => 4.3,
'stock_qty' => 20,
'approved_payments_only' => true,
) );
Did this resource help you do something awesome with Gravity Forms?
Then you'll absolutely love Gravity Perks; a suite of 47+ essential add-ons for Gravity Forms with support you can count on.
Created a form for a client the other day for booking places on a training course. They didn’t mention at the time that there are only 10 places per session, so this snippet potentially resolves that but….
The form was initially setup with a dropdown list of “options” (dates) on the “product” (training course, ÂŁ85) and then a seperate “quantity” field (number of delegates). Simplified the form so that it is a dropdown list of “products” (date) but looks as though it may still not be able to work that way since the “quantity” field is seperate but needs to relate to the “product” or “option” still.
Is there a way to achieve this, or would it need to be a seperate form per date?
Hi Steve,
Since you need to limit places per session based on a Date, we would suggest using our Limit Choices Perk. We have also snippet which will allow to group Date, Place and Quantity to limit available choices and substract the quantity selected from the total available places for each Date/Place.
Best,
Brilliant, thanks Dario.
Not been able to find the snippet to include the (standalone) Quantity field when updating the Option (date) availability as yet though.
It appears that the number of items is stored somewhere other than the ‘stock_qty’ => #, parameter in functions.php
We have several items with a value set as above and if an order is placed for that value, it returns the “Not enough stock…” message reflecting a different quantity.
We, of course, tried purging caches, reloading, etc. No effect.
Help with this, please?
HELPFUL plugin, otherwise, so thanks for it!
Hi Anne,
The stock_qty parameter is what stores the number of items, so I am not really sure why you’re getting that “Not Enough Stock” message. You can use the shortcode to display the quantity left, to confirm if the right quantity that is set in the stock_qty parameter is being used.
Also, if you have a Gravity Perks License you can get in touch with us via our support form, so we can dig into this further.
Best
Hi GravityWiz Team,
Thanks so much for making code like this available to us! I, for one, am super grateful and thankful. :-)
My question is similar to Brad Haymond’s question from January 5th.
Scott wrote a good reply that same day, but he mentioned that in order to use the snippet, we should, “paste the code below the âDo I need to modify this snippet to work with my form?â heading TO YOUR THEME and adjust the parameters accordingly.”
Would anyone be willing/able to comment how we are to add this “to our theme” if the longer code is already being added via the functions.php file? That is, do we put the full code copied from the “Download Code” or “View Code” buttons into the functions.php file and then the shorter parameters code somewhere else, or do we modify Line 56ff in the actual code which is most similar to the snippet Scott mentioned in his reply?
Thanks so much for replying whenever able, and so sorry for the extra clarification! I haven’t been able to get it to work for some reason, so this is helpful. Thanks so much!
Hi Caleb,
If you prefer to copy the entire snippet into your function.php, you will just have to copy the snippet configuration, that is the shorter parameter code, and paste it below the longer code within the function.php. Here is a documentation on how to install a snippet.
Best,
Hello, I have our ecommerce shop where people can buy individual products, they can buy gift boxes which include individual products and we use gravuty form the build a build your own box section so they pick any products to design a gift box. Is it possible to link inventory amounts for all 3 so I have 10 soap, if a person purchases for all 3 area it will reduce to 7 in stock.
Hi Brenda,
I’m not really tracking your question well, but if I understand correctly, you to want group different products and link them to an inventory? If so, then unfortunately you wouldn’t be able to do that with this snippet. With this snippet, an inventory is linked to a Product and can’t be linked to a group of Products. You may have to do some customization to the snippet to achieve what you want. In case you need a developer you can hire one from âCodeable.io.
Best,
I have my simple individual products and then I have my gravity form products which create a gift box from my products. So I have a cup as a simple product and the same cup in the gravity form. How do I set it up that when both are purchased it reduces the simple product stock count by 2?
Hi Brenda,
If you’re adding the Gravity Form to your WooCommerce product using the WooCommerce Gravity Forms Product Add-Ons plugin, you can link the quantity in the form to the WC stock using the Order Item Quantity setting. More info is available in their docs.
@Scott Buchmann what is I have 100 products in this one form. Do I add this to the product page, default qty 1 and hide it. Then when any of the products are selected it will automatically reduce the qty from the simple product stock?
Hi Brenda,
I think this particular scenario requires more specific support. If you’re a Gravity Perks customer, can you reach out to support so we can further assist you on this one?
Where does the code go to initialize a snippet? In the functions.php file? Or? Thanks!
Hi Tim,
Yes, you’ll insert the snippet into the function.php file. Please refer to our article on snippet troubleshooting for details on installing our snippets.
https://gravitywiz.com/documentation/snippet-troubleshooting/
Best,
Is it possible to have the shortcode for the Sum to have “Only_Approved_Payments” as True?
Hello Mohammad, you could change the ‘approved_payments_only’ => true, within the snippet to get this working.
Seems that the code snippet was updated without updating the instructions on this page. For example, I cannot find
new GW_Inventory
anywhere in the current snippet. I see an $args array starting on line 56 that I believe is where I want to specify my parameters, but it doesn’t match the instructions on this page.
Also, because the parameter array is different than all examples on this page and the comments, I am not sure how I can add inventory limits to multiple fields in the same form (or even across different forms). What is the correct syntax with the current snippet code to add an array of multiple fields with different limits?
Hi Brad,
We are in the process of removing usage examples from our snippets. Instead, usage examples are located in our tutorials. To use this snippet, paste the code below the “Do I need to modify this snippet to work with my form?” heading to your theme and adjust the parameters accordingly.
To apply the snippet to multiple fields in the same form or across multiple forms, check out this article.
Hi Jake,
You will definitely require some customization to the snippet, to achieve what you want. In case you need a developer to help, you can hire one from Codeable.io.
That said, this looks like a use case that should also be possible with the GP Limit Choices Perk and a snippet used to share limit across multiple fields. However, I’ll need to take a closer look at the form set up to be sure about this and assist you with the setup. In case you have an active Gravity Perks License, you can send an email with an export of the form via our support form so we can assist you further.
Best,
I was wondering if there was a way to make multiple product fields contribute to the same inventory pool. We want to cap the amount of people who register for an event. Customers can register in groups of four and get $50 off the last three people. We have it set up now to have a drop down menu that treats each number 1-4 as a different product to calculate price. I thought of creating a different product just to track inventory, but I would need a way to prepopulate it depending on the amount chosen in the drop down menu. The only way I can think of that would work would be to create four different single-product fields, but that would only work if inventory could go into the same pool. Is this capability supported? Any help would be appreciated.
How could we add support for multiple events? Say we add a radio button where they choose from 4 different event times (field IDs: 9.1 – 9.4) , then each
I was thinking of adding an if statement like this : // if ( $radio_selection_value == ‘2’ ) { new GW_Inventory_2( array( ‘form_id’ => 1, ‘field_id’ => 5, ‘stock_qty’ => 100, ‘out_of_stock_message’ => ‘Sorry, there are no more tickets!’, ‘not_enough_stock_message’ => ‘You ordered %1$s tickets. There are only %2$s tickets left.’, ‘approved_payments_only’ => false, ‘hide_form’ => false, ‘enable_notifications’ => true ) ); }
But I would need to make it support 4 different quantities, since each event would have the same initial stock_qty limit. Or should I just create a different form for each event?
Hi Nathan,
Different forms for each event would work, however this is a perfect fit for GP Limit Choices.
I’m trying to use this snippet to keep track of registration for summer camp. Is there a way to reach the limit but not hide the form but rather show a notification that they will be on a waitlist and allow them to complete the form. Thanks!
Hi Kenneth,
The snippet currently doesn’t support a waiting list. You may want to check out our GP Limit Choices Perk, that uses a snippet we have to allow a waiting list when the Limit has been reached.
I hope this helps.
Best,
Thanks for this snippet, this could probably solve my problem. Is it also possible to make the stock based on a custom post type? Let’s say I have a custom post type ‘seats’ with 5 posts which all have a status field ‘available’ or ‘reserved’, GF should check if any of these seats are available, if so the customer can book a seat.
Thanks
Hello Jochem, This should work correctly. Are you using a specific type of plugin to create the custom post types? If you would like for us to take a closer look, go ahead and send us a message through our support channel here.
I still have to build/generate the custom post type, and to be honest I still have to buy GF and Gravity Perks, so sending a support request will be difficult at the moment. But I guess I have to make some changes in the snippet to make it work right? Or should I use the Gravity Forms Populate Anything plugin?
Business case is a form to rent a ‘product’, we have 5 products of brand A and 5 products of brand B. The customer chooses a brand (if one of the products is available) and books a product, that product will be unavailable for other customers until it has returned. Is this possible with this snippet and a custom post type or does it need more customization?
Hi Jochem,
This is quite an interesting use case. Although you could use GP Populate Anything to populate a Product field with the Custom Post Type, you’ll need a way to update the status field of the Custom Post Type to reserved when an order is made. Currently, Gravity Forms Advanced Post Creation add-on doesn’t allow Post updates, so every submission of the form will create a new post. You will defintely require some custom coding, which goes beyond the functionality of this snippet, to achieve what you want. In case you need a developer to help, you can hire one from Codeable.io.
That said, if you plan to manually update the status field of the CPT when an order is made and when the book is returned, you should be able to use GP Populate Anything to populate a Product field with a list of Post saved to the CPT.
Best,
Thanks, David mentioned Populate Anything also on Twitter, so that seems like a good option.
Hi Samuel – Thanks so much! It seems to be working pretty well except for one thing. At the very bottom of the form, on the front end, a string of numbers show up. The string seems to be the number of tickets left for purchase so it’s dynamic and changes from the intial amount 1175, 70 and 65 to 0 0 0 as the tickets are sold out.
I copied the code direct and I cannot see an error in the way it is written. Is there a way to hide that? I’ve try to find the class in CSS but it doesn’t seem accessible with dev tools in Chrome.
Thoughts? Thanks.
Hello Sherry,
Thank you for writing in. This is a bit of a strange one. If you have a gravity perks account could you please send us an export of your form to our support channel found here so we could run some tests. Thank you.
Hi – I just found you guys so I don’t have a gravity perks account unfortunately. Is there another way to do this? The site is not open to the public yet.
I could take a screenhot if that helps? Would need an email to send it to.
Thanks.
This code worked perfectly for me and I am OH SO GRATEFUL! I’m not a php coder and it took me 2.5 hours to figure it all out and make my customizations but now it works and the client is happy.
Just wondering if you have any code that notifies the user when the inventory is close to its sell out. For instance, I’m using the code to sell raffle tickets by singles, and 2 types of value packs. It would be great if a purchaser would get a notice when there are only 5 single tickets left before they put in their order.
Thanks again!
Hi Sherry,
We’re glad to know how snippet worked for you đ. You can insert the shortcode,
[gravityforms action="remaining" id="1" input_id="2.3" limit="50"]
on the form page, to display the quantity remaining. This will make it possible for your users to see the quantity left before placing an order.I hope helps.
Best,
Hi I’m new to gravityforms in the past I’ve used wufoo, formstack, and form assembly. I this snippet was so important to me because my organization runs limited capacity events every year and out limit is even more critical this year with Covid-19 protocols in place.
We have had a few guests who were able to pay and checkout (authorize.net) when there were not enough tickets for the time slot. They recieved the message “You ordered 4 of this item but there are only 1 of this item left.” However they were still charged through Authorize.net, but they did not show up in our Gravity Froms entrees list and did not receive a receipt. Is there a way to make sure those who are attempting to order a time slot that is not available are not charged?
could you assist me? do I need to buy the something for this snippet to work ?
Hello Stephen, This is just a snippet that requires configuration at the bottom. You donât have to modify the snippet itself. Just the parameters with which you initialize it. Check out our help article here for some snippet troubleshooting.
Hi there, I’m using this snippet to track entries for an online art exhibition as we have a maximum number of entries allowed. I’m pretty new to php, can you advise me what I change the class ‘GW_Inventory’ to as I’m getting an error? Do I create a class for the form and target this instead? Also, if this is not a paying entry, can I just remove the line: ‘approved_payments_only’ => false,
Thanks! Rachel
Hi Rachel,
You’ll first have to copy and paste the code with the Class into your function.php file, then add the configuration with the parameters as seen in the documentation, below the code. Also, do not remove the approved payment parameter, but instead, leave it as approved_payments_onlyâ => false, if payment will not be received.
In case you’re still having difficulties setting it up, please reply with the error message are you getting?
Best,
Hey Wiz-team!
This looks perfect for a form I’m working on for a client’s website. I have a Pro license for GravityPerks and was hoping to install this functionality using that, but I don’t see it listed in the GP “Install Perks” window.
Any help would be greatly appreciated!
Hello Carter, This plugin will not show up in your install perks window as it is a snippet. Because it is a snippet, you will need to install this in your themes functions.php file and modify the snippet to meet your needs. If you need more assistance with this one, check out our snippet troubleshooting here as well as reach out to us through our support channel here.
Does this work if I have multiple products, each with their own quantities?
Hi Tyler,
Yep! You can instantiate the class multiple times on the same form for each of the different product fields.
How do I apply a class-based snippet to different (or the same) forms?
How can you reset the stock quantity once it reaches 0? I don’t want the user to have to create a new form and edit the functions file.
Hello J, Would you like this to happen immediately or after a day? You can reset the inventory daily via the following steps:
Add a Date field to your form. Set the Default Value of this field to use the {date_mdy} merge tag. Set the Visibility of this field to Hidden. Add a âfield_groupâ parameter to your snippet configuration where the â1â is the ID of your Date field: âfield_groupâ => array( 1 ) This will make the inventory specific to the desired product and the current date.
Thanks for the reply! Ideally, it should happen after 1 week. I’m trying to create an even registration with limited seat numbers and have it reset after the event occurs or manually.
Hi Jack,
You can reset the stock quantity by trashing the submitted entries. So when you remove an entry, the number of seats available will be increased by 1.
I hope this helps.
Best,
I think this is what i require, i.e. several products that can be ordered on the day and when qty reached sold out but also need it to reset every day. I am a novice developer ( meaning im a designer with a little knowledge lol). Can you be more specific on how i would add this to the above snippet ( i.e. can you write it for me please) Thanks in advance for any help
one other quick question, could the snippet be altered for delivery date rather than the order date – thanks
Hi Alistair,
Assuming the ID for your Date field is 2, you would add the parameter like this:
The Date field can correspond to any date you’d like, including delivery date. What the field group does is tie the inventory to the specific date selected. So each date has its own stock quantity.