Fill Gravity Forms Choices From Your Posts
Fills Gravity Forms drop-down, radio and checkbox fields with the titles of your posts, pages or a custom post type, so the choices update when you publish content.
Opens WPIDE on
Code
$wpide_gf_populate = function ( $form ) {
foreach ( $form['fields'] as $field ) {
if ( ! in_array( $field->type, array( 'select', 'radio', 'checkbox', 'multiselect' ), true ) || ! preg_match( '/\bpopulate-([a-z0-9_-]+)\b/', (string) $field->cssClass, $m ) ) {
continue;
}
$type = 'posts' === $m[1] ? 'post' : $m[1];
if ( ! post_type_exists( $type ) ) {
continue;
}
$cache = 'wpide_gf_choices_' . $type;
$choices = get_transient( $cache );
if ( false === $choices ) {
$choices = array();
$ids = get_posts( array( 'post_type' => $type, 'post_status' => 'publish', 'numberposts' => 200, 'orderby' => 'title', 'order' => 'ASC', 'fields' => 'ids', 'no_found_rows' => true ) );
foreach ( $ids as $id ) {
$title = wp_strip_all_tags( get_the_title( $id ) );
$choices[] = array( 'text' => $title, 'value' => $title );
}
set_transient( $cache, $choices, HOUR_IN_SECONDS );
}
$field->choices = $choices;
if ( 'checkbox' === $field->type ) {
$inputs = array();
foreach ( $choices as $i => $choice ) {
$inputs[] = array( 'id' => $field->id . '.' . ( $i + 1 + (int) floor( $i / 9 ) ), 'label' => $choice['text'] );
}
$field->inputs = $inputs;
}
}
return $form;
};
add_filter( 'gform_pre_render', $wpide_gf_populate );
add_filter( 'gform_pre_validation', $wpide_gf_populate );
add_filter( 'gform_pre_submission_filter', $wpide_gf_populate );
add_filter( 'gform_admin_pre_render', $wpide_gf_populate );
add_action( 'save_post', function ( $post_id, $post ) {
delete_transient( 'wpide_gf_choices_' . $post->post_type );
}, 10, 2 );
Notes
Give the field the CSS class populate-posts (or populate-<post type>, such as populate-product); the list is cached for an hour and refreshed when posts change.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.