Search code examples
phphtmlwordpressthumbnailscodex

WordPress get post thumbnails in a custom pattern


Right now I have for each post two sizes for thumbnail:

$big = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'thumbnail_600x200' );
$small = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'thumbnail_200x100' );

What I am trying to achieve is to display posts using this next pattern:

Post 1 - [big thumbail]
Post 2 - [small thumbail]
Post 3 - [small thumbail]
Post 4 - [big thumbail]
Post 5 - [small thumbail]
Post 6 - [small thumbail]

Actually posts will be shown big - small - small - big - small -small and so on.

Any idea? Thank you

This is my post foreach:

<?php foreach ($posts as $post) { 
    $big = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'thumbnail_600x200' );
    $small = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'thumbnail_200x100' );

    if ( $big ) { ?>
        <img src="<?php echo $big['0']; ?>" />
    <?php }else{ ?>
        <img src="http://placehold.it/600x200/7f8c8d/ffffff" alt="Featured image missing"/>
    <?php } ?>
<?php } ?>

Solution

  • Make a counter outside the function.

    Inside the function, increment the counter. But before that, check if it countr % 3 == 0.

    If so, show the big thumbnail.

    <?php
     $counter = 0;
     foreach ($posts as $post) {  
            if($counter %3 == 0)
            {
               $big = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'thumbnail_600x200' );
            }else{
               $small = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'thumbnail_200x100' );
            }
    
        if ( $big ) { ?>
            <img src="<?php echo $big['0']; ?>" />
        <?php }else{ ?>
            <img src="http://placehold.it/600x200/7f8c8d/ffffff" alt="Featured image missing"/>
        <?php } ?>
      counter++; //increase the counter
    <?php } ?>