Distribute Gallery Images Every nth in Loop

I have added an acf image gallery for archive terms and I would like to take those images and insert one image from the gallery every 3 posts in the term archive. This is what I have so far but I am not yet getting them to distribute sequentially every 3 posts.

1-2-3 posts
Image 1
3-4-5 posts
Image 2

// get the current taxonomy term
$queried_object = get_queried_object();
$taxonomy = $queried_object->taxonomy;
$term_id = $queried_object->term_id;
$images = get_field(‘term_gallery’, $taxonomy .’_’ . $term_id); //image ids
$size = ‘full’; // (thumbnail, medium, large, full or custom size)

$counter = 1;

if ( have_posts() ) :
while ( have_posts() ) : the_post();

get_template_part( ‘template-parts/content’, get_post_type() );
?>

<?php if( $images ): ?>

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

<?php if($counter % 3 == 0): ?>

<div class=”image-<?php echo $counter;?>”>
<?php echo wp_get_attachment_image( $image_id, $size ); ?>
</div>

<?php endif;?>

<?php endforeach; ?>

<?php endif;?>

<?php

$counter++;

endwhile;

endif;

Read more here:: Distribute Gallery Images Every nth in Loop

Leave a Reply

Your email address will not be published. Required fields are marked *