Field pre-population is a handy feature when working with forms. It often happens to have a select field that needs to be populated from dynamic values from a database query, an external API or a CSV file.
If you are using Ninja Forms – one of my favorites WordPress forms plugins – here is how to do it.
Assign a key to your target field
We will use a filter to pre-populate our field, and the filter needs to know which filed it should affect. We can target field by ID, as in Ninja forms field IDs are unique, but even better to target by key, as we can assign it and make it semantically relevant.
The right filter to achieve the goal is:
List field options are passed through this filter before rendering in front-end, so we can use it to set or modify the values presented.
Code the callback function
A filter hook needs a callback function, and here is where the magic happens!
An excellent example of a callback function to populate a list field from a database query can be this one:
Of course, the $options variable can be populated by data from any source. If our source contains no value, will be displayed the value from the form’s settings, so we can set a placeholder there.
The function can be placed in our function.php file, in a functionality plugin or we can use a snippets manager.