Display HTML only if Custom Field has a Value

I am working with a plugin called Advanced Custom Fields.

I am looking for help with code for my custom post type template, which is displaying some repeater field data. I have HTML wrapping each sub-field. Sometimes there will be no value for one or more of the sub-fields.

Read More

How to NOT display the HTML that is wrapping the sub-fields, if no value exists for the sub-field?

In the below code, the SPAN tag for the sub fields of “measurement” and “amount” should HIDE if no value exists for the sub-field.

My code is as follows:

<?php 
    if(get_field('ingredients-list'))
    {
    echo '<ul class="ingredientsList">';

        while(has_sub_field('ingredients-list'))
    {
    echo '<li class="ingredient" itemprop="ingredients"> <label for="">' . get_sub_field('quantity') . '&nbsp; <span class="amount">' . get_sub_field('measurement') . '</span> ' . '<span class="name">&nbsp;'. get_sub_field('ingredient_name') .'</span><span class="notes">&nbsp;' . get_sub_field('notes')  . ' </span></label></li>';
     }

         echo '</ul>';
}    
?>

Related posts

Leave a Reply

1 comment

  1. You can use the “get_sub_field” to test for the subfields. If nothing is returned and they are empty, it won’t show the content associated with the if statement.

    <?php
    if ( get_field('ingredients-list') )
    {
        echo '<ul class="ingredientsList">';
        while ( has_sub_field('ingredients-list') )
        {
            echo '<li class="ingredient" itemprop="ingredients">';
                echo '<label for="">' . get_sub_field('quantity') . '&nbsp; ';
                    if ( get_sub_field('measurement') ) echo '<span class="amount">' . get_sub_field('measurement') . '</span> ';
                    if ( get_sub_field('ingredient_name') ) echo '<span class="name">&nbsp;'. get_sub_field('ingredient_name') .'</span>';
                    if ( get_sub_field('measurement') ) echo '<span class="notes">&nbsp;' . get_sub_field('notes')  . ' </span>';
                echo '</label>';
            echo '</li>';
        }
        echo '</ul>';
    }
    ?>