Populate Gravity Form with Post Type Values

Gravity forms is great an excellent plugin, and has tons of addons that you can use to further enhance it’s functionality on your website.

I ran into an issue recently, where I needed values from a Custom Post Type without needing to update any of the Post content using the Gravity Forms > Post Field options.

To get around this, I modified the Dynamically Populating Drop Down Fields found here.

add_filter( 'gform_pre_render_4', 'populate_posts' ); // update gform value with your form ID
add_filter( 'gform_pre_validation_4', 'populate_posts' ); // update gform value with your form ID
add_filter( 'gform_pre_submission_filter_4', 'populate_posts' ); // update gform value with your form ID
add_filter( 'gform_admin_pre_render_4', 'populate_posts' ); // update gform value with your form ID
function populate_posts( $form ) {

    foreach ( $form['fields'] as &$field ) {

        if ( $field->type != 'choices' || strpos( $field->cssClass, 'css_school' ) === false ) { // change to the type of field you are using (checkbox = select, radio = choices, etc)
            continue;
        }

        $args = array(
	    	'posts_per_page' => -1,
	    	'post_type' => 'school', // any post type
	    	'post_status' => 'publish',
	    	'orderby' => 'title',
	    	'order' => 'asc',
        );
        
        $posts = get_posts( $args );

        $choices = array();

        foreach ( $posts as $post ) {
            $choices[] = array( 
            	'text' => $post->post_title, 
            	'value' => $post->post_title 
            );
        }

        // update 'Select a Post' to whatever you'd like the instructive option to be
        $field->placeholder = 'Select School';
        $field->choices = $choices;

    }

    return $form;
}

Leave a Reply

katherine as a flat graphic icon

About Me

I’m an African / Ojibwe First Nations Web Developer living in Winnipeg, Manitoba.

Visit the Tips and Blog to see what I’m working on.