Skip to content

Instantly share code, notes, and snippets.

@jetsloth
Last active April 24, 2024 00:32
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 jetsloth/25f9f249211234f9f4edba42095558fb to your computer and use it in GitHub Desktop.
Save jetsloth/25f9f249211234f9f4edba42095558fb to your computer and use it in GitHub Desktop.
An example of dynamically populating Enhanced Choices from posts
<?php
add_filter( 'gform_pre_render', 'populate_enhanced_choices_from_posts' );
add_filter( 'gform_pre_validation', 'populate_enhanced_choices_from_posts' );
add_filter( 'gform_pre_submission_filter', 'populate_enhanced_choices_from_posts' );
add_filter( 'gform_admin_pre_render', 'populate_enhanced_choices_from_posts' );
function populate_enhanced_choices_from_posts( $form ) {
// update form and field ID to suit
$FORM_ID = 1;
$FIELD_ID = 1;
if ( ! function_exists( 'gf_enhanced_choices' ) || $form['id'] != $FORM_ID ) {
return $form;
}
foreach ( $form['fields'] as &$field ) {
if ( $field->id != $FIELD_ID || ! gf_enhanced_choices()->field_supports_enhanced_choices( $field ) ) {
continue;
}
$field = gf_enhanced_choices()->field_enable_enhanced_choices( $field );
$choices = array();
$inputs = array();
$input_id = 1;
$posts = get_posts( 'numberposts=-1&post_status=publish' );
foreach ( $posts as $post ) {
//skipping index that are multiples of 10 (multiples of 10 create problems as the input IDs)
if ( $input_id % 10 == 0 ) {
$input_id ++;
}
$choice = array( 'text' => $post->post_title, 'value' => (string) $post->ID );
$categories = get_the_category( $post->IO );
$featured_image = get_the_post_thumbnail_url( $post->ID, 'full' );
if ( empty( $featured_image ) ) {
$featured_image = gf_enhanced_choices()->placeholder_image();
}
$choice = gf_enhanced_choices()->choice_add_components( $choice, array(
array(
'type' => 'image',
'src' => $featured_image,
'alt' => $post->post_title,
),
array(
'type' => 'pill',
'text' => ( ! empty( $categories ) ) ? $categories[0]->name : $post->post_title,
),
array(
'type' => 'label',
),
array(
'type' => 'paragraph',
'text' => get_the_excerpt( $post->ID ),
),
array(
'type' => 'button',
'text' => "Select",
),
) );
$inputs[] = array( 'label' => $choice['text'], 'id' => "{$field->id}.{$input_id}" );
$choices[] = $choice;
}
$field->choices = $choices;
if ( $field->get_input_type() == "checkbox" ) {
$field->inputs = $inputs;
}
}
return $form;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment