Last active
June 11, 2019 16:34
-
-
Save leepettijohn/403267277c4f1e7ec29bec75dcc9c39b to your computer and use it in GitHub Desktop.
Gravity Forms - Dropdown populated with posts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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