The WooCommerce Gravity Forms Product Add-ons extension allows you to add some very powerful customization options to your WooCommerce products. However, the form must be added on a per-product basis. This works fine for most use-cases but there are cases where it may be desirable to attach the form to all products or to all products in a given category. This can be done dynamically with a little help from the WordPress provided filter named get_post_metadata here. When you add a Gravity Form to your WooCommerce product, then information is stored in the post meta for that product so by using a filter, it is possible to ‘short circuit’ the meta retrieval function and return something custom. Any non-null return value will short-circuit the function.
Before you get started on the code, however, you will need the serialized string that is stored in the database. Take these steps:
- Attach a form to one of your products – documentation here
- via phpMyAdmin (or the Adminer plugin) find the product meta in the wp_postmeta table – copy the value for the _gravity_form_data key.
- In the snippet below, replace YOUR_SERIALIZED_STRING with the serialized string that you copied from the database (leave the single quotes in place).
- That’s it – the same form will now be attached to all your products.
That code can be tweaked if needed to add conditional logic to check against a product category or other conditions as appropriate.
Not sure what to do with code snippets? See What Do I Do With These Code Snippets?