Support

Account

Home Forums Front-end Issues Conditional "if (get_field())" shows empty field

Solving

Conditional "if (get_field())" shows empty field

  • I imported a bunch of posts with custom fields using WP All Import and their ACF add-on. It worked great and the fields were populated correctly. However, two of the fields are multi-select fields, and these fields display even if they are empty — UNLESS I open the post and manually hit “Update”. This only happens with the multiple select field. Here’s my code:

    <?php $awards = get_field('awards'); // multi select field
    
    if ($awards) { ?> 
    									          
       <b>Awards:</b>
       <?php echo implode(', ', $awards);
    
    } ?>

    With the above code, it shows the “Awards:” label even when the field is empty. If I manually click “Update” on the post, then it correctly hides “Awards:” because the field is empty.

    I use the exact same code format for all the other text and date fields, and it works fine. Why does it require hitting update for the select fields, and is there a way to fix this?

    Thanks!

  • Hi @lsterling03

    ACF creates field references on the database once the value has been saved and these do not exist since the data was imported to your db.
    I would suggest that you pass the value of the affected field to the update_field() function as described on this page: https://www.advancedcustomfields.com/resources/update_field/

  • Hi James, thank you. Do you know why this would only affect the multiple select field, though? It did not require me to save the post to create the field references for any of the standard text fields, date fields or single-select fields that I imported via the same method.

    Thanks!

  • Hi @lsterling03

    This is because multiple select field save data as a serialized array unlike standard text fields. The field reference will be useful for formatting the value.

Viewing 4 posts - 1 through 4 (of 4 total)

The topic ‘Conditional "if (get_field())" shows empty field’ is closed to new replies.