Support

Account

Home Forums General Issues How to loop through select field with value and label?

Solving

How to loop through select field with value and label?

  • Hello, I havent been able to figure this out, and was wondering if you could help.

    I have a select field, that allows multiple selections. I need to output a button for each selection.

    I tried a few different things, here is my latest iteration:

     <?php
    
              if (have_rows('show_filter_buttons') ) : 
                while(have_rows('show_filter_buttons') ): the_row(); 
    
                  $field = get_sub_field_object('show_filter_buttons');
                  $value = $field['value'];
                  $label = $field['choices'][ $value ];
                  
                  ?>
    
                  <a href="javascript:void(0)" class="btn btn-danger filter<?php echo $value; ?>"><?php echo $label; ?></a>
    
                <?php endwhile; ?>
    
              <?php endif; ?>

    As far as I can tell the loop is working, its just the values and labels that aren’t working. If I select six I can see six buttons, they just dont have text.

    **Edit – I dont know if this matters, but this field is in a flexible content field.

  • I believe with get_sub_field_object you have to pass the field key, which is different than the field name.

    Info on get_sub_field_object is here: https://www.advancedcustomfields.com/resources/get_sub_field_object/

    Info on displaying field keys is here:
    https://thestizmedia.com/show-field-keys-acf-pro/

  • Also, if it is a select field the value of the field may be returning an array

    an example of doing this for a select field is shown on this page https://www.advancedcustomfields.com/resources/get_sub_field_object/

  • This was way farking easier than I was making this out:

    
    <?php
                  $filter_buttons = get_sub_field('show_filter_buttons');
                  
                  foreach ( $filter_buttons as $button ) :
                  ?>
    
                  <a href="javascript:void(0)" class="btn btn-danger filter<?php echo $button['value']; ?>"><?php echo $button['label']; ?></a>
    
                <?php endforeach; ?>
Viewing 4 posts - 1 through 4 (of 4 total)

The topic ‘How to loop through select field with value and label?’ is closed to new replies.