Matthew Jones Matthew Jones - 20 days ago 4x
MySQL Question

How can I set multiple Gravity Forms values without doing a new database query for each one?

I have user information stored in a separate database from my Wordpress installation. I'm writing a plugin that queries this database and pre-fills values in a specific gravity form.

It looks like the following filter does what I need:

add_filter("gform_field_value_$PARAMETER", "FUNCTION");

The problem with this is that I need to call a function for each parameter value. That means that I query the database for each value.

So if I have eight pre-filled values, the database gets queried eight times. That seems inefficient.

Is there a way that I can query the database once, get all the values I need, then pass back the variables to the filters?


Here is my preferred way to handle this. Wrap your code in a class and store your query results in a variable in that class. You can then check if that variable already contains data and if so, simply return that already retrieved data rather than querying the database again.

class My_GF_Field_Values {

    var $data = null;

    function __construct() {

        add_filter( 'gform_field_value_param1', array( $this, 'func1' ) );
        add_filter( 'gform_field_value_param2', array( $this, 'func2' ) );


    function func1() {

        $data = $this->get_data();

        return $data['param1'];

    function func2() {

        $data = $this->get_data();

        return $data['param2'];

    function get_data() {

        if( $this->data == null ) {
            $this->data = array(); // actually do your query and get the data

        return $this->data;