Skip to content

Instantly share code, notes, and snippets.

@leepettijohn
Last active June 11, 2019 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leepettijohn/403267277c4f1e7ec29bec75dcc9c39b to your computer and use it in GitHub Desktop.
Save leepettijohn/403267277c4f1e7ec29bec75dcc9c39b to your computer and use it in GitHub Desktop.
Gravity Forms - Dropdown populated with posts
// https://docs.gravityforms.com/dynamically-populating-drop-down-fields/
/* Instructions
- Create a form
- Add a "Dropdown" field
- Add "populate-posts" as the CSS class
*/
add_filter( 'gform_pre_render_51', 'populate_posts' );
add_filter( 'gform_pre_validation_51', 'populate_posts' );
add_filter( 'gform_pre_submission_filter_51', 'populate_posts' );
add_filter( 'gform_admin_pre_render_51', 'populate_posts' );
function populate_posts( $form ) {
foreach ( $form['fields'] as &$field ) {
if ( $field->type != 'select' || 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
$posts = get_posts( 'numberposts=-1&post_status=publish&post_type=post' );
$choices = array();
foreach ( $posts as $post ) {
$choices[] = array( 'text' => $post->post_title, 'value' => $post->ID );
}
// update 'Select a Post' to whatever you'd like the instructive option to be
$field->placeholder = 'Select a Post';
$field->choices = $choices;
}
return $form;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment