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.
Thank you for this code. I am using this on a form where there are a limited number of add on tickets (using gravity forms product) that can be sold as part of a registration. How can I show the quantity of add on tickets remaining by this product?
Hi Karie,
You can use a shortcode similar to this “[gravityforms action="remaining" id="1" input_id="2.3" limit="50"]” to show the tickets left, below the form. But you can also check out our GP Limit Choices Perk, that will allow you to show the remaining limit by the product choices.
Best,
Hi,
i have 3 different fields with quantities. But when one of them is sold out, the out of stock message is shown. Even when there is quantity left in one of the other 2 fields.
I tried https://gravitywiz.com/documentation/apply-class-based-snippet-different-forms/ , but i am not sure if i used it right. This is how it looks now: http://snippi.com/s/lhou448
With this, the snippet isn’t working anymore. Do i have to add this ‘modifier’ too?
Thank you already !
Lena
Hello Lena, Thank you for that snippi link to your classes. It looks like your fields are not being linked to the quantity field and just the field as a whole. So you would need 16.3,28.3,29.3 to target the quantity of each field. I have just tested this and it should be working correctly.😃
Hi,
on the following page two items are sold out “Sitzsack in der vordersten Reihe”, “Garten-Loge (VIP-Ticket)”. You can find the soldout message “Leider gibt es zu dieser Kategorie keine Tickets mehr! (not available anymore)”. The prices for the sold out items are 53 CHF and 69CHF, together 122 CHF.
Even if they are sold out, the total sum in the and is always with these 122 CHF on the top. I used the attached code in function.php
May you help me with that?
Kind regards Gregor
CODE: http://snippi.com/s/krweapq
Hello Gregor, I am not 100% following. Are the items still showing up or is the price still showing at the end? Are you using the pricing in another calculation on your form? This one would require a bit more investigation to find out the total sum is being added with extra numbers. If you have a Gravity Perks license could you please reach out to us through our support channel and we would be more than happy to take a deeper dive into this.
Hi Ryan
the items are still showing but instead of the price field it shows the “no items in stock” available message. The price of the ticket is added to the total sum at the end oft the form. You can try it out here: https://j4fun.ch/shaketix/26-8/
Hi Gregor,
Better Inventory doesn’t expect both a
field_id
and aninput_id
. You should only include thefield_id
in the args, and set that ID to the quantity field. For example:http://snippi.com/s/bh45h4r
If you’re still running into trouble with the snippet after making that adjustment, we’re happy to help via support if you have a Gravity Perks Advanced or Pro license.
I am using Drop Down with Pricing Fields (Products), is there a way with this code or with your paid plugin to connect it to inventory of another product? Let say I have a kit that has products A&B in it and there is an option to substitute B to C for a higher price. I also have stand alone products B & C that have their own inventory levels, can I use the inventory in the B & C products to show that in the drop down? Let say that if customer wants to choose option “C” and it is out of stock as a stand alone product then customer would see a message out of stock?
Hello Igor, this is an interesting question. Gravity Forms Limit Choices is a great way to provide inventory per choice in a Drop Down field. This can be combined with our very powerful Field Groups snippet to make the inventory specific to the choice and any other variations selected in other fields including options + other fields.
Is it possible to add a custom message, if there are „as example“ only 5 pieces in stock left? Right now I only get a “out of stock“ „not enough stock” message.
Kind regards Gregor
Hey Gregor, you would have to alter the parameters with which you initialize it. So, in this case, you would alter the ‘not_enough_stock_message’ parameter to meet your needs. Please note that when you modify, you are not changing the code, rather you will be adding this to the bottom with your custom code.
Hi, I am using this snippet, and I thought all was working well, however when I reached my stock limit of one of my items, the value of the out of stock item was added to the total of the form, despite the out of stock message being displayed and therefore the product could not be selected.
The item was not being listed on the order summary, just the charge added to the total.
This only appears to be occurring with items which are linked to quantity fields; items which are just product fields appear to be performing correctly, ie not adding cost once stock is exhausted.
Any ideas?
Hi, been trying a few times, but I don’t get it to work. What am I missing?
These are the settings: http://snippi.com/s/xvhrmj8 The form ID is 23, the quantity field ID is 53. Si I would expect that if you select AANTAL +10 an notification should pop-up?
Hello Mario, It looks as if yoou may not be targeting the quantity field completely. Try 53.3 and see if this would work for you.
First changed this to this http://snippi.com/s/orbv8lj
Then to this: http://snippi.com/s/2cvh7yi
Still not working :-(
Hello Mario, Generally you should be able to accomplish this with using something like this http://snippi.com/s/iaiegj0. Do you currently have a Gravity Perks License? If so you could send us a ticket with your form and we can take a deeper dive into this.
Sadly enough not working with your feedback. I’ve opened a support-ticket. thx for your help!
Hi,
First the snippets works great. But i have another question. Is the stock calculated per day? Or do we need to adjust the stock every single day?
For a client we created a form (under construction) for rental purposes. The client has 10 vehicles to rent with different timeslots. So when will the stock be deducted? After the payment and how can the customer “fill his own stock again”?
Thanks in advance.
Regards, David
Hey David, these are counted per entry. If you remove an entry the stock will return to normal. The stock will be deducted as soon as the form submits, so if you have a payment gateway that requires validation before submitting the data, the entry will be counted after completion.
I have found what looks to be a compatibility issue with GF Stripe addon. I am running the same settings across multiple forms using an array of form ids > http://snippi.com/s/9j2ke79 If I change hide_form to true and one fo the forms reaches the submission limit, the credit card number and CVC, postcode inputs are removed from all other forms just leaving the credit card name input for the CC field.
For some reason the hide_form wrongly removes those inputs from other forms. Any ideas why this would be happening?
Actually, please ignore/delete this. Seems the issue isn’t related to the snippet as it remains when removed.
Hey Nik, Sounds good! Let us know if you have any other questions regarding the snippets. 😀
Hi, I am getting a fatal error when using this snippet. http://snippi.com/s/p9dfnvd It’s installed in functions.php, I have tried your example with the same issue (with the opening php tag removed).
This is the error Got error ‘PHP message: PHP Fatal error: Uncaught Error: Class ‘GW_Inventory’ not found in /home/xyz/webapps/xyx/wp-content/themes/hello-theme-child-master/functions.php:26\nStack trace:\n#0 /home/xyz/webapps/xyz/wp-settings.php(497): include()\n#1 /home/xyz/webapps/xyz/wp-config.php(85): require_once(‘/home/xyz…’)\n#2 /home/xyz/webapps/xyz/wp-load.php(37): require_once(‘/home/xyz…’)\n#3 /home/xyz/webapps/xyz/wp-admin/admin-ajax.php(22): require_once(‘/home/xyz…’)\n#4 {main}\n thrown in /home/xyz/webapps/xyz/wp-content/themes/hello-theme-child-master/functions.php on line 26′, referer: https://www.xyz.com.au/wp-admin/admin.php?page=gf_edit_forms&id=3
Any ideas why it is causing a fatal error? Thanks Nik
Hello Nik, Thanks for writing in. Have you added the full snippet https://gist.githubusercontent.com/spivurno/3749223/raw/8149483790c36b26913db8db58fb85c1cbb5e017/gw-gravity-forms-inventory.php to your functions.php? The snippet you provided should be added as a configuration at the end of the snippet above. If you run into any other issues we do have a snippet troubleshooting guide found here.
Thanks Ryan, my bad, I thought GW_Inventory was part of the core. Makes complete sense and works thank you!
Hey Nik, No worries, happy it works. Have a great day!
Hey guys, I’m thrilled to use this snippet however I’m a bit confused about the parameters portion. I understand how to include this in my function.php file. The parameter code, do you append this to the main code? Where do you paste it if not to the function.php?
Hello, excellent question. You would add the new GW_Inventory( array() ); parameters to the end of the snippet. Whatever fields you alter there will then be modified within the snippet allowing you to be able to customize it to you needs.😀
Hey Ryan, TYVM! I thought so however I am not successful. Seems I’m triggering a critical error and the white screen of death. I have three product fields with quantities enabled and the ID as 5.3, 6.3 & 7.3 following the multiple instance same form format. I downloaded the snippet from github as well. I commented out two of the field IDs and then all but still getting wsd. What am I missing?
Hi, Oh no! This might help: https://gravitywiz.com/documentation/apply-class-based-snippet-different-forms/. It may be because you are adding multiple instances to the same form.
Yes, I saw that link in an earlier comment and used the same form multiple instances example by indicating the same form ID in each case. When that didn’t work, I commented out 2 of them to no avail. Just not sure where to look so I’ll start over. Thanks!
OMG! I figured it out. How simple. When I pasted the downloaded snippet code to my function.php, I included the <?php tag to the code already there. Duh. It’s nice to let folks know their solutions, it helps others.
I tried this on a multisite in the subsite’s child theme folder and got the following error: “Uncaught Error: Class ‘event_Inventory’ not found in /home/…” Does this work in multisite?
Hello Colleen, This snippet should work on a multisite but it would depend on your setup. If you like you could drop us a support request and we could take a closer look at your site. Thank you!
Hey.
Thank you for the plugin. Very useful.
Im using ACF for the tickets limit. Would you be able to tell me how can I add stock_qty as a acf field ( which essentially various from page to page)?
Thank you.
I think I have the answer:
https://snippets.cacher.io/snippet/b26d448f78d66a6df9ce
Thank you! :)
I think I rushed with the answer slightly, sorry.
It seems that the get_field is not picking the value from the post as it cat see the ID
How can I get the value of a field in function file?
Thank you.
Hey Dom, you could set the parameter as a function. Something like
'stock_qty' => function() { global $post; get_post_meta( $post->id, 'stock', true ); }
This would get the “stock” custom field for any post on which the form is displayed. If you still have questions regarding this could you drop us a support request for this? We’ll be happy to dig in.Hello!
I would this snippet be used for multiple forms? Would you just have to copy the form specific part of the code or can it really only be used for 1 form?
Hi Chelsea, this might help: https://gravitywiz.com/documentation/apply-class-based-snippet-different-forms/
Hi there any chance to show that how much inventory is remaining, like below
http://prntscr.com/qws4pt
Thanks!
Hi Thanks so much for this. How can we use the spaces left shortcode to fill a fields default value to use for conditionals please
Show the quantity remaining for the specified input and limit. [gravityforms action="remaining" id="1" input_id="2.3" limit="50"]
The shortcode can’t be used for this, but Limit Choices supports conditional logic on the number of remaining choices.
Hi this code snippet creates a fatal error- i get this in my error log PHP Warning: strpos(): Empty needle in /home4/hiddeob4/public_html/wp-includes/functions.php on line 4360
Does this have to do with your little snipit or is it some deeper issue?
Hi Steve, start by checking that you have the snippet installed correctly. If that doesn’t resolve the error, drop us a support request and we’ll dig into this for you.
Any chance this can work on a select/dropdown field? Was hoping to have an option where the user could select from one event date or the other (and each event date is limited to 4 registrations). If I’m reading this correctly, it only seems to work on a single field (that doesn’t have variations). I have a bit of a complicated situation where I’m using a WooCommerce product that can only be purchased 8 times (a workshop) and then there is an option add-on where users can buy it 4x per date – so it’s almost like I have dual stock management going on where I need to manage stock for the master product and then also at the variation level but I don’t believe there is a way for WooCommerce to do that either. That’s why I was hoping within the Gravity Forms Product add-on I could manage the stock there somehow.
Hi Justin, Gravity Forms Limit Choices is a great way to provide inventory per choice in a Drop Down field. This can be combined with our very powerful Field Groups snippet to make the inventory specific to the choice and any other variations selected in other fields (included a Date field or a Drop Down field with available dates).
Hi David,
Thank you for this code. I am using gravity forms product add-ons in Woocommerce and someone can place an order for more stock than is available, so your code snippet works great.
However what I need to do is vary the stock quantity (used in the GW_Inventory parameters) based around the current product stock quantity. No matter what I try to do I cannot get the code to recognise either the product id or the post id.
If I hard code the product id then something like this works fine.
http://snippi.com/s/dchklx9
I can happily output the post / product id to the page but when I try the same in your GW_Inventory parameters it returns a null value, and the main code fails.
Anything you could do to point me in the right direction would be much appreciated.
Thanks
Hi Jonathan, here’s an example of the preferred method for current-post-specific stock quantities: http://snippi.com/s/84wz11f
I have this integrated with a payment gateway Stripe. In the new release of Gravity Forms Stripe, we have the option to have the secure checkout be redirected to a “stripe checkout” form ( hosted by Stripe ) I have found that the inventory is subtracted even if the payment isn’t complete..
Is there a way to only take inventory if payment is successful ?
Thanks.
Hi Josh, you’re looking for the “approved_payments_only” parameter.
There it is. I apologize this was right in front of me :-)