Dynamically Populating Drop Down

I am using Gravity Forms to dynamically populate the values in a select with custom post types titles using the code found here. I am trying to add the featured image to the option tag, after the title:

add_filter( 'gform_pre_render_12', 'populate_posts' );
add_filter( 'gform_pre_validation_12', 'populate_posts' );
add_filter( 'gform_pre_submission_filter_12', 'populate_posts' );
add_filter( 'gform_admin_pre_render_12', 'populate_posts' );
function populate_posts( $form ) {
    foreach ( $form['fields'] as &$field ) {
        if ( $field->type != 'select' || strpos( $field->cssClass, 'cpt-name' ) === false ) {
        $posts = get_posts( 'post_type=agent-name&numberposts=-1&post_status=publish&orderby=name&order=ASC' );
        $choices = array();
        foreach ( $posts as $post ) {

            $featured_image = get_the_post_thumbnail($post->ID, 'thumbnail');

            $choices[] = array( 
                'text' => $post->post_title . $featured_image, 
                'value' => $post->post_title 
        // update 'Select a Post' to whatever you'd like the instructive option to be
        $field->placeholder = 'Select a Post';
        $field->choices = $choices;
    return $form;

I tried to add the featured image it after the option text but it’s printing &lt;img&gt; instead of <img>. Even so, when I edit this in the code inspector to add the correct img tag, it still does not appear.

Is it possible to add the featured image to an option tag?

Hey Marc, including images in <option> tags is not supported (quick demo). It doesn’t look like Chosen (the library that powers Gravity Forms “Enhanced UI” option) supports it either.

This might be a good start for implementing an alternate solution:

Depending on how many options you have, a Radio Button field may be an another path forward. Obviously, this would change the UX quite a bit…

We’re (Gravity Wiz) actively working on a solution for including images in Drop Down fields as part of our upcoming Advanced Select perk. Feel free to sign up for our newsletter to say in the loop.

Thanks for the reply David.

Looks like no images for now…

1 Like