ACF get field label in custom code

I have some custom code in order to display my custom fields the way I want.

Unfortunately, with this code I can’t seem to access the $field['label']. I tried various ways but don’t really know how to achieve this.

<?php
    $fields = get_fields();
    if( $fields ): ?>
        <ul>
        <?php
            foreach( $fields as $name => $value ):
                if (stripos($name, 'isbn') !== false) : ?>
                    <li><b><?php echo $name['label']; ?></b> <?php echo $value; ?></li>
                <?php endif;
            endforeach; ?>
        </ul>
    <?php endif; ?>

1 Answer
1

Try this, which worked for me:

<?php
    $fields = get_field_objects(); // I changed from get_fields()
    if( $fields ): ?>
        <ul>
        <?php
            // I changed $value to $field (i.e. the variable name)
            foreach( $fields as $name => $field ):
                if (stripos($name, 'isbn') !== false) : ?>
                    <li><b><?php echo $field['label']; ?></b> <?php echo $field['value']; ?></li>
                <?php endif;
            endforeach; ?>
        </ul>
    <?php endif; ?>

So referring to the $field in the code, $field['label'] is the field label (e.g. “Book ISBN”), and $field['value'] is the field value. Note though, that the field value could be an array, so simply echo-ing it would (likely throw a PHP warning and) give you a “Array”.

See https://www.advancedcustomfields.com/resources/get_field_objects/ if you need help with the get_field_objects() function.

PS: If you only want to get the label of a single field and not all fields (of the current/target post/user/etc.), you can use get_field_object() instead.

Leave a Comment