0

I'm trying to change the layout of my front-page after x amount of posts, then returning to the original layout as shown in the image below.

<?php
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$query = new WP_Query( 
    array(
        'posts_per_page' => 7,
        'paged' => $paged
    ) 
);

if ( $query->have_posts() ) : ?>    

    <div> // container 1
        <div> //container 2

        <?php   
            $count = 1;
            while ( $query->have_posts() ) : $query->the_post(); 
        ?>

            <?php echo the_post_thumbnail(); ?>
            <?php echo get_the_title(); ?>


        <?php if ( 3 === $count) { ?>

        </div> // close container 2
    </div> // close container 1

        <?php }  ?>

    <?php if ( 4 <= $count) { ?>
        // put new layout here 
    <?php } ?>

    <?php if ( 6 <= $count) { ?>
        // return to original layout
    <?php } 

    $count++; 

    endwhile; 

endif; ?>

This is a simplification of the code I currently have. Hope this question is easy to understand!

the dark grey represents new sections

the dark grey represents new sections

0

First of all you don't need any custom counter ($count variable) to achieve this. WP_Query already has such counter:

$current_post (available during The Loop) Index of the post currently being displayed.

and you can use it.

And back to your code... Your main problem is that you don't use any conditions inside while loop, but add them after the loop, so they don't do anything.

And here's how it should look like:

<?php
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$query = new WP_Query( 
    array(
        'posts_per_page' => 7,
        'paged' => $paged
    ) 
);

<?php if ( $query->have_posts() ) : // if there are any posts found ?>    
    <div><!-- section 1 -->
        <?php while ( $query->have_posts() && $query->current_post < 3 ) : $query->the_post(); ?> 
        // put layout 1 here 
        <?php endwhile; ?>
    </div>
<?php endif; ?>

<?php if ( $query->have_posts() ) : // if there are enough posts for section 2 ?>
    <div><!-- section 2 -->
        <?php while ( $query->have_posts() && $query->current_post < 6 ) : $query->the_post(); ?>
        // put layout 2 here 
        <?php endwhile; ?>        
    </div>
<?php endif; ?>

<?php if ( $query->have_posts() ) : // if there are enough posts for section 3 ?>
    <div><!-- section 3 -->
        <?php while ( $query->have_posts() ) : $query->the_post(); ?>
        // put layout 3 here 
        <?php endwhile; ?>        
    </div>
<?php endif; ?>
| improve this answer | |
  • Thank you so much for the help! Just made a small edit to what you wrote but other than that it works beautifully! – TimothyKA Sep 3 '19 at 21:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.