I’ve got an array of images attached to a post, and can output them sequentually just fine:

1 2 3 4 5 6 7

How can I get three images at a time from the array, then step one image forward to create the following arrays of three images:

1 2 3

2 3 4

3 4 5

4 5 6

and so on?

Here’s my code:

global $rental;

$images = get_children( array(
    'post_parent' => $rental_id,
    'post_status' => 'inherit',
    'post_type' => 'attachment',
    'post_mime_type' => 'image',
    'order' => 'ASC',
    'orderby' => 'menu_order ID'
) );

if ($images) :

    $i = 0;

    foreach ($images as $attachment_id => $image) :

        $i++;

        $img_url = wp_get_attachment_url( $image->ID );

        ?>

        <div class="item <?php if($i == 1){echo ' active';} ?> class="<?php echo $i; ?>"">
            <img src="https://wordpress.stackexchange.com/questions/250150/<?php echo $img_url; ?>" title="<?php echo $i; ?>" />
        </div>

    <?php endforeach; ?>
<?php endif;

2 Answers
2

You can split your array using the following

$array = array(1,2,3,4,5,6);
$number_of_elements = 3;

$count = count( $array );
$split = array();
for ( $i = 0; $i <= $count - 1; $i++ ) {
    $slices = array_slice( $array, $i , $number_of_elements);
    if ( count( $slices ) != $number_of_elements )
        break;

    $split[] = $slices;
}

print_r( $split );

Leave a Reply

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