2

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; ?>
7
  • Maybe you meant $value['label'] and not $name['label'] ?
    – Sally CJ
    Jul 25, 2018 at 12:33
  • @SallyCJ no, that'S not working either.. It results in: "Warning: Illegal string offset 'label' in..."
    – sonja
    Jul 25, 2018 at 12:50
  • Try adding var_dump($fields); after $fields = get_fields(); and check its output. Is there the label item?
    – Sally CJ
    Jul 25, 2018 at 12:54
  • @SallyCJ hmm no it's not there! How do I get it?
    – sonja
    Jul 25, 2018 at 13:03
  • Ah I see it now. I thought 'label' was a field. xD Use get_field_objects() and not get_fields(). =)
    – Sally CJ
    Jul 25, 2018 at 13:14

1 Answer 1

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.

1
  • 1
    thank you so much! That's exactly what I was looking for!
    – sonja
    Jul 25, 2018 at 13:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.