当 php 字段没有值时隐藏代码

  • 本文关键字:隐藏 代码 php 字段 php
  • 更新时间 :
  • 英文 :


如果PHP字段值为空,我需要隐藏代码。

这是代码:

<?php if( get_field('volunteer_causes') ): ?>   
                <div class="program-single-volunteer-causes">
                    <h4>Volunteer Causes</h4>
                    <?php
                    $terms = get_field('volunteer_causes');
                    if( $terms ): ?>
                        <ul>
                        <?php foreach( $terms as $term ): ?>
                            <li>
                                <span><?php echo $term ?></span>
                            </li>
                        <?php endforeach; ?>
                        </ul>
                    <?php endif; ?>
                </div><!--program-single-volunteer-causes-->

正如它一样,如果" oldunteer_causes"字段中没有值,则HTML将保留。

我尝试使用包含HTML的每行使用回声。
示例:<?php echo '<h4>Volunteer Causes</h4>'; ?>
但是,这一切都没有改变。

当字段中没有值时,此方法可以删除所有代码:
<?php if( !empty(the_field('volunteer_causes')) ): ?>
...但是,当值出现时,我的HTML丢失了。

您可以通过在if中分配来缩短此内容,并且您可能已经忘记了关闭第一个if

<?php if( $terms = get_field('volunteer_causes') ): ?>   
    <div class="program-single-volunteer-causes">
        <h4>Volunteer Causes</h4>
            <ul>
            <?php foreach( $terms as $term ): ?>
                <li>
                    <span><?php echo $term ?></span>
                </li>
            <?php endforeach; ?>
            </ul>
    </div>
<?php endif; ?>

尝试此

<div class="program-single-volunteer-causes">
  <?php
   $terms = get_field('volunteer_causes');
   if (!empty($terms)) {
    echo
     '<h4>Volunteer Causes</h4>
     <ul>';
     foreach ($terms as $term) {
      echo
       '<li><span>' . $term . '</span></li>';
     }
     echo
     '</ul>';
   } else {
     echo '<p>No Record Found</p>';
   } 
 ?>
</div>  

我最终在自由职业者网站上支付了5美元以使其工作。这就是他们想到的,它可以工作!

<?php
$volunteer_causes = get_field('volunteer_causes');
if($volunteer_causes[0]){ ?>
<div class="program-single-volunteer-causes">
<h4>Volunteer Causes</h4>
<?php
$terms = get_field('volunteer_causes');
if( $terms ): ?>
<ul>
<?php foreach( $terms as $term ): ?>
<li>
<span><?php echo $term ?></span>
</li>
<?php endforeach; ?>
</ul>
<?php endif;
}
?>
</div>

最新更新