Hi! Im trying to query all image fields from a Post Type to create a “random gallery”. The problem is that my gallery has 4 colums, so I can create the loop only at first column. How can I continue the loop until the last column??
the_query
col-md-3
loop / if / while
image 2
image 6
image 4
endif / endwhile
col-md-3
continue loop...
image 1
image 3
image 5
col-md-3...
I appreciate any help. Thank you!


I get what you’re trying to do, and I’ll post the code below with how to do it using a flat array but it’s unclear what the_query
is or how it relates to Advanced Custom Fields. Until the actual code you’re using is posted the below may be a good starting point for you:
<?php
$image_array = query(); // Whatever you're using to query the images
// Ensure have an image array to work with
if( ! empty( $image_array ) ) {
$per_block = 4;
$total_items = count( $image_array );
foreach( $image_array as $index => $image_id ) {
$nice_index = $index + 1; // Arrays start at 0 but count and per block start at 1. Calculate once.
$start = ( 0 == $index % 4 ); // Calculate if we're at the start
$end = ( $nice_index == $per_block || $nice_index == $total_items ); // Check if we've hit the end
// Display Opening Tag
if( $start ) {
print( '<div class="col-md-3">' );
}
// Display image by ID
wp_get_attachment_image( $image_id, 'full' );
// Display Closing Tag
if( $end ) {
print( '</div>' );
}
} // END Foreach
} // END Conditional