Search code examples
phpwordpressposts

Get every second post in WordPress loop


I need to seperate loops in two colums and want to skip every second loop in each loop. At the end I need a view like this:

Loop 1

  • Post 1
  • Post 3
  • Post 5

Loop 2

  • Post 2
  • Post 4
  • Post 6

Is that possible?

My current loop:

<?php $args = array (
                'nopaging'               => true,
                'posts_per_page'         => '999',
                'ignore_sticky_posts'    => false,
            );

            $query_row_1 = new WP_Query( $args ); if ( $query_row_1->have_posts() ) : ?>

                <?php while ( $query_row_1->have_posts() ) : $query_row_1->the_post(); ?>
                    <?php the_title(); ?>
                <?php endwhile; ?>

            <?php else : endif; wp_reset_postdata(); ?>

Solution

  • As I already commented:

    You can declare a counter variable like this:

    $counter = 0;
    

    And in the while loop insert these four lines at the beginning:

    $counter++;
    if($counter % 2)
    {
        continue;
    }
    

    This increases the counter with one and checks whether the counter is even or not. Since the outcome is only 0 or 1 it can be directly used in the if confition because this represents true or false. If it if odd the while loops jumps to the next run and if it is even the rest of the loop continues. If you want to switch even and off make the if statement like this if(!($counter % 2))