【问题标题】:ACF count gallery imagesACF 计数图库图片
【发布时间】:2018-10-09 15:13:25
【问题描述】:

我正在尝试使用 ACF 库字段制作不同大小的图像网格。

我以前通过计算行数在转发器字段中设法做到这一点,但无法调整它以与图库字段一起使用。

我的目标是使用 2 种不同的图像尺寸制作 10 张图像的网格。

  • 图片 1、2、3、6、7、8 将是一种尺寸
  • 图片 4、5、9、10 的尺寸会不同

我当前的标记是:

<?php 
    $images = get_field('home-image-grid');
    $size = 'full';
    if( $images ): 
?>
    <ul>
        <?php foreach( $images as $image ): ?>
            <li>
                <?php echo wp_get_attachment_image( $image['ID'], $size ); ?>
            </li>
        <?php endforeach; ?>
    </ul>
<?php endif; ?>

我已经尝试过之前使用的标记与转发器字段,但这只会输出图像 1。

<?php 
    $i = 1;
    $images = get_field('home-image-grid');
    $size = 'full';
    if( $images ): 
?>

    <?php foreach( $images as $image ): ?>

        <?php if ( $i == 1 ) { ?>
            image 1
        <?php } elseif ( $i == 2 ) { ?>
            image 2
        <?php } elseif ( $i == 3 ) { ?>
            image 3
        <?php } elseif ( $i == 4 ) { ?>
            image 4
        <?php } ?>

    <?php endforeach; ?>

<?php endif; ?>

我认为这是因为 foreach 语句。我怎样才能让它工作?

【问题讨论】:

  • 我不确定这是否是您发布的完整代码,但您肯定应该在 endforeach 之前用 $i++ 递增 $i 吗?目前,在您的循环中,$i 始终等于 1。

标签: php wordpress advanced-custom-fields acfpro


【解决方案1】:

这项工作将在图库或转发器字段中完成,都返回数组。

您只是忘记在循环中添加迭代 $i++

所以你的循环会是这样的

<?php foreach( $images as $image ): ?>

    <?php if ( $i == 1 ) { ?>
        image 1
    <?php } elseif ( $i == 2 ) { ?>
        image 2
    <?php } elseif ( $i == 3 ) { ?>
        image 3
    <?php } elseif ( $i == 4 ) { ?>
        image 4
    <?php } 
     $i++;
     endforeach; ?>

另外,如果您的数组索引没有任何复杂的条件,那么您可以使用带有数组索引的 foreach 循环,例如

<?php foreach( $images as $index => $image ): ?>

    <?php if ( $index == 0 ) { ?>
        image 1
    <?php } elseif ( $index == 1 ) { ?>
        image 2
    <?php } elseif ( $index == 2 ) { ?>
        image 3
    <?php } elseif ( $index == 3 ) { ?>
        image 4
    <?php } 
     endforeach; ?>

【讨论】:

    【解决方案2】:

    如果 2 个分离的背景图片:

    <div class="d-container"><div class="diagonal diagonal--left" style="background-image: url(
    	<?php
    		if ( $course_zig_images ) :
    			foreach ( $course_zig_images as $index => $course_zig_image ) :
    				if ($index == 0 ) :
    					echo $course_zig_image['url'];
    				endif;
    			endforeach;
    		endif;
    	?>
    	)"></div></div>
      
      
      <div class="d-container"><div class="diagonal diagonal--right" style="background-image: url(
    	<?php
    	if ( $course_zig_images ) :
    		foreach ( $course_zig_images as $index => $course_zig_image ) :
    			if ($index == 1 ) :
    				echo $course_zig_image['url'];
    			endif;
    		endforeach;
    	endif;
    	?>
    	)"></div></div>

    【讨论】:

      猜你喜欢
      • 2018-10-11
      • 2020-07-05
      • 2015-04-05
      • 1970-01-01
      • 2020-03-29
      • 1970-01-01
      • 1970-01-01
      • 2017-04-16
      • 1970-01-01
      相关资源
      最近更新 更多