如果字段为空,如何创建不显示字段的条件?

How do I create a condition that will not display a field if the field is empty?

我正在使用高级自定义字段 (ACF)。如果字段为空,我不想显示 ACF 转发器字段 the_sub_field('feature_image_post');。如果该字段为空,我将字段包装在 div 中并使用 CSS 编写了一个 display = none,但我确信有更好的方法可以做到这一点。我的逻辑好像不行。

 <?php

        // check if the repeater field has rows of data

        if( have_rows('repeat_field') ):

          // loop through the rows of data
            while ( have_rows('repeat_field') ) : the_row();

                // display a sub field value

                echo '<span class="place-name">';
                  the_sub_field('place_name');
                echo '</span>';


      if (!empty (get_sub_field('feature_image_post')))  {

       echo '<div class="post-feature" style="display:block;">'; 
       echo the_sub_field('feature_image_post'); 
       echo '</div>';

      } 

      else {
       echo '<div class="post-feature" style="display:none;">' 
       echo the_sub_field('feature_image_post'); 
       echo '</div>';

      }
            endwhile;

        else :

            // no rows found

        endif;
if (! empty(get_sub_field('feature_image_post'))) {
    echo '<div class="post-feature" style="display:block;">';
    the_sub_field('feature_image_post'); 
    echo '</div>';
}

就是这样。在这种情况下 get_sub_field('feature_image_post') 为空,它将跳过整个部分。

据我所知 - ACF 中的 the_ 表示它显示数据,因此在此之前您不需要 echo

并且请始终检查您是否使用 ; 关闭了 echo,因为在示例中您没有。

这里不需要 else 语句。如果该字段尚未设置,那么您根本不会显示任何内容。

我的方法是使用 get_sub_field() 并将结果作为条件的一部分分配给变量。

ACF 中图像的默认 return 值是一个值数组,因此我假设这就是您所拥有的值。

示例:

if ( $feature_image_post = get_sub_field( 'feature_image_post' ) )  {
    echo '<div class="post-feature">'; 
    printf( '<img src="%s" alt="%s" />', esc_url( $feature_image_post['url'] ), esc_attr( $feature_image_post['title'] ) );
    echo '</div>';
} 

最后要提出的一点是 get_sub_field()the_sub_field() 之间的区别。在您的原始代码中,您试图回显 the_sub_field()get_... 将 return 一个值,而 the_... 将输出它,使 echo 在该上下文中变得多余。