Friday, 29 August 2014

if field is empty hide div - the golden ticket.

Working on a project today, and came across an age-old struggle; Simon vs. Various Coding Languages. I am building out a project page using Advanced Custom Fields (for WordPress), and I built out these neat little cards, with an image, title, and blurb, and two buttons on the bottom. 

Not knowing how many cards my client would need for each section, I built out a total of 10. But what if the client only needs 8 on a particular page? There are still ugly buttons underneath a blank spot with no image or text - this will not do.
I spent 30-40 minutes noodling around jQuery and could not sort out how to hide the div if the particular field was empty. 
Chris Coyier of CSS Tricks has a good article, but I was unable to sort it out and adapt it to my situation. I am rather overwhelmed with PHP, as I am only familiar with WP's brand of PHP. 
Short of the long, here is what I found:

<?php if (get_field('region10') && get_field('region10') != "") { ?>

    <article class="one-third-space region-card">
    <img src="<?php the_field('region10-image'); ?> " alt=" <?php get_image_tag($alt); ?> ">
        <div class="text"><?php the_field('region10'); ?></div>
<a href="<?php the_field('region1-link'); ?>">
<button class="button bg-orange centre">MORE DETAILS...</button>
</a>
<button class="button bg-blue centre">RESERVE THIS TRIP</button>
</article> <?php } ?>

The fields I created are called 'region10' . The PHP is wrapped around the whole section which it will logically decide to show or hide what's inside. 
"IF THIS FIELD IS EMPTY, SHOW NOTHING (denoted by " ")"

As a front-end developer I cannot explain it any deeper than this, and I truly hope this helps.

No comments:

Post a Comment