Francis Alvin Tan
Francis Alvin Tan

Reputation: 1087

list all the label and value from a group field type in ACF

I really need some help, My problem is that I cannot show the label from a group field using ACF

Script below is displaying the name and value, I need the "Label" to be displayed and its "value" and I can't find anything.

if( have_rows('product_specifications') ): 
    while( have_rows('product_specifications') ): the_row(); 
    $subfields = get_field('product_specifications'); 
    if( $subfields ) { ?>
    <ul> 
        <?php
        foreach ($subfields as $spec => $value) {
        if ( !empty($value) ) { ?>
        <li><?php echo $spec; ?> : <?php echo $value; ?></li>
        <?php }
        } ?>
    </ul>
    <?php }
    endwhile;
endif;

Here is my current output:

lamp_type : E27
wattage : 1x 60W Max
globe_included : 1
colour_cord : Clear

when It should be:

Lamp Type : E27
Wattage : 1x 60W Max
Globe : 1
Colour Cord : Clear

Please anyone help me...

Upvotes: 1

Views: 4848

Answers (2)

Sally CJ
Sally CJ

Reputation: 15620

Use get_row() to get the sub fields:

$subfields = get_row();

And use get_sub_field_object() to get the sub field object:

$field = get_sub_field_object( $key );

So, try this: (no re-indentation so that you can easily compare with your code)

if( have_rows('product_specifications') ):
    while( have_rows('product_specifications') ): the_row();
    if( $subfields = get_row() ) { ?>
    <ul>
        <?php
        foreach ($subfields as $key => $value) {
        if ( !empty($value) ) { $field = get_sub_field_object( $key ); ?>
        <li><?php echo $field['label']; ?> : <?php echo $value; ?></li>
        <?php }
        } ?>
    </ul>
    <?php }
    endwhile;
endif;

Upvotes: 10

M. Ferguson
M. Ferguson

Reputation: 1421

What you are looking forward within the foreach loop is using the get_field_object() function.

Within here, you can get the label and value of any field.

For examples / uses of the get_field_object(), take a look at https://www.advancedcustomfields.com/resources/get_field_object/.

So, for example, you'll have:

$field = get_field_object($spec);
echo $field['label'] . ': ' . $field['value'];

Hope this helps.

Upvotes: 0

Related Questions