Support

Account

Home Forums General Issues using get_field_object but only if there are values

Solved

using get_field_object but only if there are values

  • I’m trying to use a (long list) of fields that i want to display their value and their label.

    If i wasn’t displaying their label I would do this:

    $field1 = get_field('myfirstfield');
    $field2 = get_field('mynextfield');
    $field3 = get_field('mylastfield');
    
    if ($field1) echo '<p>1st: '.$field1.'</p>';
    if ($field2) echo '<p>2nd: '.$field2.'</p>';
    if ($field3) echo '<p>3rd: '.$field3.'</p>';

    This works fine and only shows the data if the field has a value. However Now I’m trying to use a field label to so I tried this code:

    $field1 = get_field_object('myfirstfield');
    $field2 = get_field_object('mynextfield');
    $field3 = get_field_object('mylastfield');
    
    if ($field1) echo '<p>$field1['lablel']: '.$field1['value'].'</p>';
    if ($field2) echo '<p>$field2['lablel']: '.$field2['value'].'</p>';
    if ($field3) echo '<p>$field3['lablel']: '.$field3['value'].'</p>';

    However it outputs each paragraph regardless of data in the field. I know this is likely a very simple question but what am I doing wrong?
    I thought of doing this:

    $field1 = get_field('myfirstfield');
    if ($field1) {
         $field1 = get_field_object('myfirstfield');
         echo '<p>$field1['lablel']: '.$field1['value'].'</p>';
    }

    But this seems overly complex for some reason and would be hard to repeat for the 15 fields.
    I looked at get_fields() so I could simplify this as well, but don’t want to show ALL fields from the page. it did seem to show that i could pull name from just fields instead of objects.
    Is there a better way to make a for loop? (that would be just a sidenote to the question and icing on my cake)

  • 
    if ($field1['value']) echo '<p>$field1['lablel']: '.$field1['value'].'</p>';
    
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.