spliting posts into two columns

This is a continuing question from Merging a complex query with post_rewind and splitting posts into two columns

Hi, I need help with my loop. What is does is split posts into two columns.

<?php $row_start = 1; while ( $query->have_posts() ) : $query->the_post(); ?>      <?php if ( in_array( get_the_ID(), $duplicates ) ) continue; ?>         <?php if( $row_start % 2  != 0) {// odd ?>             <div class="post">                 left - <?php the_title();?><br>             </div>         <?php } ;?>         <?php if( $row_start % 2 == 0) {// even ?>             <div class="post">                 right - <?php the_title();?><br>             </div>         <?php } ;?>  <?php ++$row_start; endwhile; wp_reset_postdata(); endif; ?> 

It outputs the loop as the following:

<div class="left">post</div> <div class="left">post</div> <div class="right">post</div> <div class="left">post</div> <div class="right">post</div> <div class="left">post</div> <div class="right">post</div> 

What I would to do is to wrap all posts in a div, like the following:

<div class="left"> post post post </div> <div class="right"> post post post </div> 



Run through the loop with % for the left side first, then rewind the loop and start in on the right side.


You could always try to create 2 arrays of titles, say $left and $right, $odd and $even, or $tom and $jerry, and fill them with the titles during your loop, and print them after the loop has ended like so:

Create array

$left = $right = array();

Then unleash your loop

<?php // The loop

  if ( $query->have_posts() ) : $row_start = 1;
  while ( $query->have_posts() ) : $query->the_post();

  if ( in_array( get_the_ID(), $duplicates ) ) continue;
    if( $row_start % 2  != 0) {
      // odd: add result to $left
      $left[] = get_the_title();
    } else {
      // even: add it to $right
      $right[] = get_the_title();
    ++$row_start; endwhile; wp_reset_postdata();
  // now loop has ended and we have 2 full arrays
  // that we can print each in it's div
  print "<div class=\"left\">";
  foreach($left as $postTitle) {
    print "$postTitle <br>";
  print "</div>";
  // next column
  print "<div class=\"right\">";
  foreach($right as $postTitle) {
    print "$postTitle <br>";
  print "</div>";


I've not yet tested this but it should work (or some close variation of it). I personally would output the list of posts in unordered lists (<ul class="right or left">) and put each title in an <li>.

Good luck :)

Category: php Time: 2016-07-28 Views: 0
Tags: php query loop

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development


Front-end development


development tools

Open Platform

Javascript development

.NET development

cloud computing


Copyright (C) avrocks.com, All Rights Reserved.

processed in 0.172 (s). 12 q(s)