chaddidthis of Developer Code Snippets
1/24/2019 - 9:39 PM

Populate a form field with Custom Post Type

For Ried's Food Barn I needed the job application to be populated with the current job openings.

I found how to do this on the gravity forums, but that is for posts and select fields. This will expand on that.

This code will go into the functions.php file.

All that is needed to do, once this code is in functions:

  1. update form id
  2. change field type to what you need populated
  3. You can change the class name if you want, but 'populated-posts' needs to be the class on the input within Forms
<?php

// The 4 on these add_filters is the ID of the form you want to populate
add_filter( 'gform_pre_render_4', 'populate_posts' );
add_filter( 'gform_pre_validation_4', 'populate_posts' );
add_filter( 'gform_pre_submission_filter_4', 'populate_posts' );
add_filter( 'gform_admin_pre_render_4', 'populate_posts' );

function populate_posts( $form ) {

    foreach ( $form['fields'] as &$field ) {
	
				// Change the field type to the desired type and 'poppulate-posts' needs to be the class
				// of the field you want populated.
        if ( $field->type != 'multiselect' || strpos( $field->cssClass, 'populate-posts' ) === false ) {
            continue;
        }

        // you can add additional parameters here to alter the posts that are retrieved
        // more info: http://codex.wordpress.org/Template_Tags/get_posts
        // The post_type should be the CPT slug. You can add other parameters if you need to narrow down
        $posts = get_posts( 'post_type=job_listings' );

        $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 a Position';
        $field->choices = $choices;

    }

    return $form;
}