Recently we had a project where we had to see if a Gravity Form existed before outputting anything. The reason we had this issue was because the plugin would be on a bunch of themes, each with different form numbers. As such, if the form didn’t exist, we’d have an ugly “We Couldn’t Find The Form” text.
Gravity Forms (from our experience) didn’t have a check to see if a form with ID $id
existed, so we had to write a function to find this. The easiest way we found was interacting with the database directly.
The form is recorded in the rg_form
table, so we’re simply going to use WordPress’ $wpdb
class to run an SQL query. If we get a value back that’s bigger than 0, then we know that the from exists.
Code To Check if a Gravity Forms Exists
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | /** * How to check if a gravity form exists for a certain ID * * @link https://www.winwar.co.uk/2015/04/how-to-check-if-a-gravity-form-exists/?utm_source=codesnippet * * @param integer $id ID of the form you wish to check * @return boolean TRUE if exists, FALSE if not. */ function winwar_if_gravity_form_exists( $id ) { global $wpdb; $gravityformtablename = $wpdb->prefix . 'rg_form'; $countformssql = "SELECT COUNT( * ) FROM " . $gravityformtablename . " WHERE id = %d"; $countforms = $wpdb->get_var( $wpdb->prepare( $countformssql, $id ) ); if ( $countforms != 0 ) { return TRUE; } else { return FALSE; } } |
To use this code, simply call this within an if
statement:-
1 2 3 4 5 6 7 8 9 10 | // Check if Gravity form of ID 1 Exists if ( winwar_if_gravity_form_exists( 1 ) ) { echo "Form exists!"; } else { echo "Form doesn't exist"; } |
Let me know if you find this useful!
Comments
Polite Disclaimer: I am welcome, open and willing for corrections to be shared in the comments (with corrections being added to posts and credited), and the comments field should be used to promote discussion and make this post better. I do not know everything and if anybody finds a better way to do something, then by all means please share it below.
However, I'm unable to offer support to posts. The reason being is that WordPress has tens of thousands of plugins and millions of themes. As such, finding out exactly why code doesn't work with your setup is a long process. If you wish for me to look at your code, please use the priority support area.
Comments asking support will be left on the site, but there is no guarantee of answer.
Comments are closed.