Skip to content

Instantly share code, notes, and snippets.

@rochow
Last active October 12, 2020 22:07
Show Gist options
  • Save rochow/2f6e4fc7f460be20ebc5 to your computer and use it in GitHub Desktop.
Save rochow/2f6e4fc7f460be20ebc5 to your computer and use it in GitHub Desktop.
Populate Dropdown with Post Type
<?php
add_filter( 'gform_pre_render', 'gform_prepopluate_post_type' );
add_filter( 'gform_admin_pre_render', 'gform_prepopluate_post_type' );
function gform_prepopluate_post_type( $form ){
$post_type = 'project';
$order_by = 'title';
$order = 'ASC';
$return = 'title'; // What you want the value to be, title or id
$form_id = 2;
$field_id = 2;
// Only populate the relevant form
if( $form['id'] != $form_id ) {
return $form;
}
// Initial blank value (remove the below line if don't want)
$items[] = [ 'text' => '', 'value' => '' ];
// Fetch the relevant posts
$posts = get_posts([
'post_type' => $post_type,
'order_by' => $order_by,
'order' => $order,
'posts_per_page' => '-1'
]);
// If there's post, loop through and add them to our array
if( $posts ) {
foreach( $posts as $post ) {
$title = apply_filters( 'the_title', $post->post_title );
$value = ( 'title' == $return ) ? $title : $post->ID;
$items[] = [ 'value' => $value, 'text' => $title ];
}
}
// Loop through the fields. For the one that matches update the choices to our $items
if( $form['fields'] ) {
foreach( $form['fields'] as $field ) {
if( $field_id == $field['id'] ) {
$field['choices'] = $items;
}
}
}
return $form;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment