Checking if Custom Fields exist in WordPress

This is my first question on Stack Overflow so bear with me.

I have a WordPress site with the Advanced Custom Fields plugin installed. The site has a custom post type that has various ACF custom fields attached to it.

Read More

Not all of the custom fields are required, also some of the custom fields are grouped into their own tabular structure.

I need to check if either of 2 custom fields have content, and if they do display the table.

My PHP is fairly limited but I did some research and it should work, but its not.

The code is as follows:

<?php if (get_field( 'meeting_documents_agendas' && 'meeting_documents_minutes')) : ?>

    <?php if ( get_field( 'meeting_documents_agendas' ) ) : ?>
        <a href="<?php echo get_field('meeting_documents_agendas');?>">Download file</a>
    <? endif ?>

    <?php if ( get_field( 'meeting_documents_minutes' ) ) : ?>
        <a href="<?php echo get_field('meeting_documents_minutes');?>">Download file</a>
    <? endif ?>

<? endif ?>

Basically nothing is displaying, even if I have content in those custom fields.

Is the code right? Could it be a WordPress bug?

Related posts

Leave a Reply

2 comments

  1. Try

    <? if (get_field('meeting_documents_agendas') || get_field('meeting_documents_minutes')): ?>
    

    This means: if one or both of the fields are set, display the table.

    Don’t use && because this means that both fields must be set. Use get_field() twice because you want to logically link the results of get_fields(), not the parameters themselves.

  2. This was helpful for me as well. Though my issue was a bit different since I was using sub_fields. I needed the code to check if both sub_fields had data.

    Here’s my code.

    <?php if (get_sub_field( 'additional_link_url' ) && get_sub_field('additional_link_text') ) : ?>
    			  <br /><a target="_blank" href="<?php echo get_sub_field('additional_link_url')['url']; ?>"><?php echo get_sub_field('additional_link_text'); ?></a>
    
    <?php endif; ?>