Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

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>';
}    
?>
share|improve this question

1 Answer 1

up vote 1 down vote accepted

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>';
}
?>
share|improve this answer
1  
Thanks for your reply. There seems to be a problem with just the quantity field being repeated endlessly. Imgur –  damrakred Mar 31 '13 at 16:00
    
I had done a quick test on a flexible content field not repeater. You are correct that it isn't working with repeater, but you an use get_sub_field instead. My mistake. I updated above. –  Jake Mar 31 '13 at 23:54
1  
That works great, thank you sir! –  damrakred Apr 1 '13 at 2:24

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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