如果自定义字段为空,则不显示div

时间:2016-03-15 作者:A.Copland

我正在寻找一种更好的方法,在自定义字段为空时隐藏div。我已经知道了如何隐藏div,但我有很多自定义字段,我不想为每个字段编写代码。

(Note: I am using the Advanced Custom Fields plugin.)

所以基本上,如果下面的字段为空,我想隐藏节标题。

谢谢

<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
}    
?>

1 个回复
最合适的回答,由SO网友:Adam 整理而成

尝试以下操作:

<?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>
如果要显示或隐藏多个字段,请进一步抽象代码以满足您的需要。