I'm looking for a better way to hide a div when a custom field is empty. I've figured out how to hide the div but I have quite a few custom fields and I'd rather not write the code for each one.
(Note: I am using the Advanced Custom Fields plugin.)
So basically I want to hide the section title if the the field underneath it is empty.
Thanks
<div class="section-title">Services for Individuals</div>
<div class="section-text">
<?php the_field('services_for_individuals') ?>
</div>
</div>
<div class="section-title-business">Services for Businesses</div>
<div class="section-text">
<?php the_field('services_for_businesses') ?>
</div>
</div>
</div>
<?php
$value = get_field( "services_for_businesses" );
if ( $value ) {
echo $value;
} else {
?>
<style type="text/css">
.section-title-business {
display:none; }
</style>
<?php
}
?>
I'm looking for a better way to hide a div when a custom field is empty. I've figured out how to hide the div but I have quite a few custom fields and I'd rather not write the code for each one.
(Note: I am using the Advanced Custom Fields plugin.)
So basically I want to hide the section title if the the field underneath it is empty.
Thanks
<div class="section-title">Services for Individuals</div>
<div class="section-text">
<?php the_field('services_for_individuals') ?>
</div>
</div>
<div class="section-title-business">Services for Businesses</div>
<div class="section-text">
<?php the_field('services_for_businesses') ?>
</div>
</div>
</div>
<?php
$value = get_field( "services_for_businesses" );
if ( $value ) {
echo $value;
} else {
?>
<style type="text/css">
.section-title-business {
display:none; }
</style>
<?php
}
?>
Share
Improve this question
edited Mar 18, 2016 at 9:22
A.Copland
asked Mar 15, 2016 at 10:46
A.CoplandA.Copland
331 gold badge1 silver badge5 bronze badges
2
- Are your fields going to be nested like you have, or is each field going to be in its own DIV wrapper element? Right now you have the Services for Businesses nested inside the Services for Individuals DIV ... is that correct? You said you will have many other fields, are those nested as well? – sMyles Commented Mar 15, 2016 at 15:00
- yes each will be nested in it's own DIV there seems to a closing tag missing – A.Copland Commented Mar 18, 2016 at 9:19
1 Answer
Reset to default 5Try this:
<?php
$business_services = get_field( "services_for_businesses" );
//etc...
?>
<div class="section-title">Services for Individuals</div>
<div class="section-text">
<?php the_field('services_for_individuals') ?>
</div>
<?php if ( $business_services ) : ?>
<div class="section-title-business">Services for Businesses</div>
<div class="section-text">
<?php echo $business_services; ?>
</div>
</div>
<?php endif; ?>
</div>
Further abstract the code to meet your needs if you have more than one field to show or hide.