WordPress query display multiple titles first then content then repeat through loop

I want to have 2 columns of titles followed 2 rows of content and then repeat until query is done.

Example:

Read More
<div><?php the_title(); ?></div>
<div><?php the_title(); ?></div>

<div><?php the_content(); ?></div>
<div><?php the_content(); ?></div>


<div><?php the_title(); ?></div>
<div><?php the_title(); ?></div>

<div><?php the_content(); ?></div>
<div><?php the_content(); ?></div>

Here is my current code

<?php  
$teams = new WP_Query(array(  
'post_type' =>  'team-post'
)  
);  
if ($teams->have_posts()) : while  ($teams->have_posts()) : $teams->the_post();?>

<?php if( $teams->current_post%2 == 0 ) echo "n".'<div class="row">'."n"; ?>

<div class="col-md-6"><?php the_title(); ?></div>

<?php if( $teams->current_post%2 == 1 || $teams->current_post == $teams->post_count-1 ) echo '</div> <!--/.row-->'."n"; ?>

<div class="col-md-12"><?php the_content(); ?></div>

<?php endwhile; endif; wp_reset_query();?>

The problem with the query is that it runs through each entry and outputs first TITLE then CONTENT which is the norm. Id like to be able to have 2 TITLES first then the CONTENT for those 2 entries, then repeat.

Related posts

1 comment

  1. You can’t do what you want to do by looping through the posts that way. You’d need to write a for loop and use an incrementing number to get the two posts at a time.

    If it were me I’d take a look at the HTML/CSS structure and see if there’s a better way to achieve the desired effect but if you’re pretty set on a PHP solution something like this will work:

    $teams = new WP_Query( array( 'post_type' => 'team-post' ) );
    
    $total_posts = count( $teams->posts );
    
    for ( $i = 0; $i < $total_posts; $i += 2 ) {
    
        $left_post = $teams->posts[ $i ];
    
        $right_post = ( isset( $teams->posts[ $i + 1 ] ) ) ? $teams->posts[ $i + 1 ] : false;
        ?>
        <div class="row">
            <div class="col-md-6"><?php echo get_the_title( $left_post->ID ); ?></div>
            <?php if ( $right_post ) { ?>
                <div class="col-md-6"><?php echo get_the_title( $right_post->ID ); ?></div>
            <?php } ?>
    
            <div class="col-md-12"><?php echo apply_filters( 'the_content', $left_post->post_content ); ?></div>
            <?php if ( $right_post ) { ?>
                <div class="col-md-12"><?php echo apply_filters( 'the_content', $right_post->post_content ); ?></div>
            <?php } ?>
        </div>
        <?php
    }
    

    This also takes into account the possibility of an odd number of posts.

Comments are closed.