Support

Account

Home Forums Front-end Issues Hide HTML when field in empty

Solved

Hide HTML when field in empty

  • Hi, I’m pretty new to this so bear with me 😉

    I have created a new group that I use for my option page. In this group I added a field called ‘social_media’ that has the repeater function. Next I have added three sub fields and I use the social media field for my options page.

    On the options page the user can add links to the social media pages that there using. This link will show in the frontend the following way:

    <?php if( have_rows('social_media', 'option') ): ?>
        <?php while( have_rows('social_media', 'option') ): the_row(); ?>
    	    <ul>
    	        <li><a href="<?php the_sub_field('facebook'); ?>">Facebook</a></li>
    	        <li><a href="<?php the_sub_field('Twitter'); ?>">Twitter</a></li>
    	        <li><a href="<?php the_sub_field('LinkedIn'); ?>">LinkedIn</a></li>
    	    </ul>
        <?php endwhile; ?>
    <?php endif; ?>

    This works perfect but I am still not happy. I’m trying to hide everything when there is no link placed in the sub field. I’m however still seeing the HTML (UL, LI, A) surrouning everything. Can someone point me in the right direction?

  • Hi @soroshd

    You need some more if-statements 🙂
    Save all values to variables, then check wether ANY of those exists. then check each one.

    
    <?php if( have_rows('social_media', 'option') ): ?>
        <?php while( have_rows('social_media', 'option') ): the_row(); ?>
        	<?php 
    	    $fb = get_sub_field('facebook'); 
    	    $tw = get_sub_field('Twitter');
    	    $li = get_sub_field('LinkedIn');
    	    ?>
    	    <?php if( $fb || $tw || $li ): ?>
    	    <ul>
    	    	<?php if( $fb ): ?>
    		        <li><a href="<?php echo $fb; ?>">Facebook</a></li>
    	        <?php endif; ?>
    	        <?php if( $tw ): ?>
    	        <li><a href="<?php echo $tw; ?>">Twitter</a></li>
    	        <?php endif; ?>
    	        <?php if( $li ): ?>
    		        <li><a href="<?php echo $li; ?>">LinkedIn</a></li>
    		    <?php endif; ?>
    	    </ul>
    	    <?php endif; ?>
        <?php endwhile; ?>
    <?php endif; ?>
    
  • Thanks you very much @jonathan! I couldn’t get my mind around it, but it works perfect now. For people that look for the same solution: the awesome code that Jonathan has provided is missing one endif; statement three rows from the bottom 🙂

    Thanks again, looking forward to play some more with ACF!

  • No problem 🙂

    Code is a learning process and we all get a little bit better each time. I’ve edited the snippet to account for the runaway endif so it should be fine to copy now.

    Please feel free to let us know if you need further assistance.
    Have a nice day.

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

The topic ‘Hide HTML when field in empty’ is closed to new replies.