Dynamically Populate Gravity Forms Drop Down Fields

Gravity forms is one of the easiest form creation plugin to use with WordPress. With its drag and drop feature building a form take only a couple of clicks and you are on your way. Apart from being easy to use using the interface , it also has a array of hooks and filters which you can use to customize the behaviour of the form or any part of it.

Today we are going to have a look at how to populate a dropdown using a post type as the source.

For example your theme is setup with a custom post hotel rooms. Now on your contact form or booking form you want to show the room types that is avaible to book. You can go and manually add each room using the fields within the dropdown form element. But we dont want to do that.

How to add dynamic drop down population via filters

The first thing we’re going to do is add a new drop down field to our form. To keep it nice and clean lets remove all the default items in there.

Next we will need to add a class to the dropdown. Click the Appearance tab and in the custom css field lets add: hotel-rooms-dropdown.

You can make that anything you like as long as you make sure to use the same name in  the code that we will be adding to the functions.php file.

Remember to save the form and now we can move on to the code.

So open the funtions.php file
And add this in there:

add_filter('gform_pre_render', 'populate_hotel_rooms');
add_filter( 'gform_pre_validation', 'populate_hotel_rooms' );
add_filter( 'gform_admin_pre_render', 'populate_hotel_rooms' );
//Note: this will allow for the labels to be used during the submission process in case values are enabled
add_filter( 'gform_pre_submission_filter', 'populate_hotel_rooms' );

function populate_hotel_rooms( $form ) {


    foreach ( $form['fields'] as &$field ) {
        if ( $field->type != 'select' || strpos( $field->cssClass, 'movies-dropdown' ) === false ) {

        // you can add additional parameters here to alter the posts that are retrieved
        // more info: http://codex.wordpress.org/Template_Tags/get_posts
        $room_ids = get_posts('fields=ids&posts_per_page=-1&post_status=publish&post_type=hotel-rooms-dropdown&order=asc&orderby=title');

        // update 'Not listed Here' to whatever you'd like the instructive option to be
        $choices = array(array('text' => 'Not listed Here', 'value' => 0 ));

        foreach ( $room_ids as $room_id ) {
            $choices[] = array( 'text' => get_the_title( $room_id ), 'value' => $room_id, 'isSelected' => false );

        $field['choices'] = $choices;
    return $form;

Save the functions.php file and now you’re ready to roll.
For more information and details about all of the Gravity Forms features, you can always refer to their official API Functions documentation.

Recent Posts

Leave a Comment

Contact Us

We're not around right now. But you can send us an email and we'll get back to you, asap.

Start typing and press Enter to search