Search code examples
phpwordpressgravity-forms-plugin

Gravity forms: ACF fields for radio button labels


I am trying to create Gravity forms radio buttons where label is being entered in ACF text fields.

I have tried using Gravity forms ACF live merge tag. However, when using merge tag the output comes out like:

<label for="choice_16_11_0" id="label_16_11_0">{custom_field:valg_1}</label>

The merge tag is just written in plain text and not the actual text from the ACF field. Therefore I figured I had to use gform_field_choice_markup_pre_render filter in order to override the label. I have followed the example found in Gravity forms documentation. My code:

add_filter( 'gform_field_choice_markup_pre_render_16_11', function ( $choice_markup, $choice, $field, $value ) {
    if ( $field->get_input_type() == 'radio' ) :

        switch ( rgar( $choice, 'text' ) ) {
            case "Valg 1":
                $description = get_field('valg_1');
                break;
            case "Valg 2":
                $description = get_field('valg_2');
                break;
            case "Valg 3":
                $description = get_field('valg_3');
                break;
        }

    endif;

    return str_replace( "</label>", "</label>$description", $choice_markup );

}, 10, 4 );

16 is my form ID and 11 is the field ID for my radio buttons. However, my code doesn't seem to be doing anything. Any pointers on what I might be missing ??


Solution

  • Try taking $description out of the quotes inside the return.

    FYI if you are trying to replace the choice in its entirety, I would replace the current text value (otherwise your code will simply add a suffix to your existing label).

    if ( $field->get_input_type() == 'radio' ) :
    
            switch ( rgar( $choice, 'text' ) ) {
                case "Valg 1":
                    $description = get_field('valg_1');
                    $current = "Valg 1";
                    break;
                case "Valg 2":
                    $description = get_field('valg_2');
                    $current = "Valg 2";
                    break;
                case "Valg 3":
                    $description = get_field('valg_3');
                    $current = "Valg 3";
                    break;
            }
    
        endif;
    
        return str_replace( ">".$current, ">".$description, $choice_markup);